You are on page 1of 24

Learn C# Programming Tutorial Lesson 1 - Your First Program

Requirements

To be able to do this tutorial you will need to have a good understanding of how to use a computer. You
will also need to either get Microsoft Visual Studio.Net or download the free C# compiler from Microsoft's
website.

Writing the code

You have 2 choices when you write a C# program and they are to use the Visual Studio IDE to write your
code or to use notepad. We will be using notepad. You can start by typing the following line in notepad.

using System;

The above code makes it easier for us to use certain commands in C#. Make sure that you use capital and
small letters properly because C# is case sensitive. Next we must declare the program class. To do this you
must use the class keyword and give the class a name. We will call it First. You must then put in some curly
brackets to surround the class's contents.

using System;

class First

Now we have to create the Main function. The Main function is where a program starts executing
commands from. You must always create a Main function or else your program will not be able to run.
Here is how to create the Main function.

using System;

class First

public static void Main()

The public keyword means that the function is accessible by anything. static means that the function must
stay in memory. void is the return type. Main is the name of the function. The brackets are where you put
optional program parameters but we have not for this example. You again use curly brackets to surround
the commands in the Main function. The last thing we will do is use the Console.WriteLine command to
write Hello on the screen.
using System;

class First

public static void Main()

Console.WriteLine("Hello");

A comment is something that is used to make a program easier to understand and is ignored and does not
affect the way a program runs. A comment goes between a /* and a */ or after a //. Here is how you would
comment the above program.

/* This program writes the

word Hello on the screen */

using System;

class First // class declaration

public static void Main() // Main function. Program starts here

Console.WriteLine("Hello"); // Print Hello

Save the file as First.cs and remember where you saved it.

Compiling and running

We are now ready to compile the program. When you compile a program it means you take the source
code that you have just written and convert it to an executable program file. To do this we must open the
Visual Studio.NET command prompt and enter the following.

csc First.cs

If you get errors while compiling then you need to go through this tutorial again and find out where your
mistakes are. If there are no errors then it means that your program compiled successfully. To run the
program enter its name at the command prompt. You should see the word Hello printed on the screen.
Congratulations! You have just written your first C# program.

Learn C# Programming Tutorial Lesson 2 - Variables and Constants


What is a variable?

A variable is a block in memory that you can use in a program to store data. You can store different types
of data such as numbers and words.

Using variables

Before you can use a variable you must declare it. To declare a variable you must first choose what data
type it is. If you want to store a number then you must use the int data type. You must then choose a name
for the variable. We will use the name MyInt in the following example.

int MyInt;

To store a value in a variable you must use an =. Here is an example of how to store the value 5 inside an
integer variable.

MyInt = 5;

You can store a value inside a variable when you declare it. This is called initializing the variable.

int MyInt = 5;

To declare 2 or more variables at once just separate them with a comma.

int i,j;

You can perform calculations on variables using a +, -, *(multiply), or /(divide). When you perform a
calculation you must put the variable that is going to store the value on the left of the = and the calculation
on the right. Here are some examples.

int a,b,c,d;

a = 1 + 2;

b = 2 - 1;

c = 5 * 3;

d = 10 / 5;

The double data type is used for storing numbers that include a decimal point.

double MyDouble = 1.2;

The char data type stores single letters and special characters. You need to put a char inside single quotes
when using them. This is because numbers can also be characters but when a number is a character then it
is not a number anymore.

char MyChar = 'c';


A string is a data type that can store many characters together. You must put strings in double quotes
when using them. You can also join 2 strings together using a +.

string MyString = "This";

string s = MyString + " is a string";

The bool data type can only store either a true or a false.

bool MyBool = true;

MyBool = false;

Type conversions

You can't just store a char type in an integer variable. You have to perform a type conversion if you want to
do something like this. If you are converting between numbers like an integer and a double then all you
need to do is put the type you want to convert to in brackets in front of the value that must be converted.

double d = 7.5;

int i = (int)d;

If you want to convert between types like a string and a number then you need to use special conversion
functions. There is a special class called Convert that has methods for converting between data types.

int i = 5;

string s = Convert.ToString(i);

double d = Convert.ToDouble(i);

Constants

Constants are values that can't have their value changed. By making a certain number a constant you are
giving it a name which means more than the value by itself. You have to set the value of a constant when
you declare it.

const double PI = 3.14;

Input and output

The Console.ReadLine command is used for reading values from the keyboard and putting them into a
variable. Console.WriteLine prints the value of a variable. Here is an example program that asks the user to
enter something and then stores the entered number in a variable and then prints it out again.

Console.Write("Enter something: ");

string s = Console.ReadLine();

Console.WriteLine(s);
Learn C# Programming Tutorial Lesson 3 – Decisions
if statement

The if statement is used when you want to make a decision in your program. Here is an example of how
you would check if the user enters the correct password.

Console.Write("Enter password: ");

string password;

password = Console.ReadLine();

if (password == "abc")

Console.Write("The password is correct");

You will see from the example above that the if statement starts with the if keyword. It is followed by the
condition in brackets. Notice that when you compare 2 values you must use 2 equals signs instead of 1. The
code after the brackets is run only if the condition evaluates to true. This means that if the password
entered by the user is equal to "abc" then it will print the message telling the user that the password is
correct.

If you want to run some code for when the condition is false then you must use the else keyword.

if (password == "abc")

Console.Write("The password is correct");

else

Console.Write("The password is wrong");

If you want to use more than one command for either the true or the false part then you must put them all
between curly brackets.

if (password == "abc")

Console.Write("The password is correct");

Console.Write("You may use the program");

else

Console.Write("The password is wrong");

Console.Write("Try again");

}
Not only can you check if values are equal but you can also check if they are not equal among other things.
Here are the comparisons that you can use.

==Equal

!=Not equal

>Greater than

>=Greater than or equal to

<Less than

<=Less than or equal to

You can use && (AND) to make 2 or more comparisons at once. Here is an example of how to check that
both the username and password entered by a user are correct.

string username,password;

Console.Write();

username = Console.ReadLine();

Console.Write();

password = Console.ReadLine();

if (username == "abc" && password == "def")

Console.WriteLine("Access Granted");

You can also use || (OR) to check if one of the comparisons is equal to true. Here is a simple example
where the value of i is not equal to 5 but the value of j is equal to 6 which means the condition evaluates to
true.

int i = 5;

int j = 6;

if (i == 5 || j == 6)

Console.WriteLine("Either i == 5 or j == 6");

switch

The switch statement is used to compare 1 value to many others at the same time instead of having to
write out a whole lot of if statements. Here is an example that tells the user what they entered if they
entered either a 1, 2 or 3 and prints a default message if they didn't enter any of those numbers.

Console.Write("Enter a number: ");

string s = Console.ReadLine();

switch(s)
{

case "1":

Console.WriteLine("You entered 1");

break;

case "2":

Console.WriteLine("You entered 2");

break;

case "3":

Console.WriteLine("You entered 3");

break;

default:

Console.WriteLine("You entered some other number");

break;

The value to be compared against all the others goes in brackets after the switch keyword. All other parts
of the switch statement must go between brackets. A case must be used for each value that must be
compared followed by the code to run if the values are equal. The break keyword must be used to exit the
switch without doing any of the other comparisons. The default is run if no values are matched.

Learn C# Programming Tutorial Lesson 4 - Loops


A loop is something that is used to repeat a section of code as many times as you want. If you wanted to
print Hello 100 times then you could use 100 lines of code or you can do the same in only a few lines using
a loop.

For Loop

The for loop counts from one number to another number. You start a for loop with the for keyword which
is followed by brackets. The first section inside the brackets is where you set the starting value of the loop
counter variable. The second section is the loop end condition. The third is where the loop counter is
incremented. The code to run for the loop goes after the brackets.

Here is an example of how to repeat printing Hello 5 times. First we declare a loop counter variable called
x. At the for loop we initialize the loop counter to 1. The loop will keep repeating while x is less than or
equal to 5. The x++ increments x by 1 each time the loop repeats. x-- would be used if you wanted to
decrement. You can also use x = x + 1 instead of x++ if you really want to.

int x;

for (x = 1; x <= 5; x++)


Console.WriteLine("Hello");

It is possible to declare the loop variable inside the loop variable initialization part of the for loop and it is
also a good idea to do this.

for (int x = 1; x <= 5; x++)

Console.WriteLine("Hello");

While Loop

A while loop repeats itself while its condition is true. You need to use your own loop counter in a while
loop which means you must increment it inside the loop each time. A while loop starts with the while
keyword. This is followed by the condition in brackets. The loop code goes after this. If you want to use
more than 1 command inside any loop you must surround them with curly brackets. Here is an example
that prints Hello 5 times.

int y = 1;

while (y <= 5)

Console.WriteLine("Hello");

y++;

Do While Loop

The do while loop is similar to the while loop except that the condition is tested at the bottom of the loop.
You start a do while loop with the do keyword. The while goes after the loop code. You must remember to
put a semi-colon after the while at the bottom. We will look at a different example this time that keeps
asking the user to enter a password until he gets it correct.

string password;

do

Console.WriteLine("Please enter the password: ");

password = Console.ReadLine();

while (password != "abc");

break and continue

You can use the break command to exit a loop at any time. For the following example we will create an
infinite loop. This loop would usually print Hello forever but we will use the break command to stop it after
it has printed Hello once.

while (1 == 1)
{

Console.WriteLine("Hello");

break;

The continue command will jump ahead to the next iteration of the loop. The following example will not
print Hello because the continue command sends control back to the top of the loop each time.

for (int z = 1; z <= 5; z++)

continue;

Console.WriteLine("Hello");

Learn C# Programming Tutorial Lesson 5 - Arrays


Imagine that you want to enter 10 numbers and calculate their average. You would need to declare 10
variables to do this. That is a lot of variables to have to declare and you still have to read the values in one
at a time for each one. An easier way of doing this is to use an array. An array is many variables grouped
together under one name.

To declare an array you must first have the data type followed immediately by empty square brackets.
After that you put the array's name. Here is how to declare an array of integers called arr.

int[] arr;

This is not an array yet but just a reference to an array. You must set the number of dimensions using the
new keyword followed by the data type again with square brackets after it that contain the number of
elements you want in the array. The following example creates an array with 3 elements.

int[] arr = new int[3];

The following table will help you imagine what an array looks like.

Element Number Value

0 5

1 12

2 7

You must use square brackets after the name of the array to access its values. Inside the square brackets
you put the number of the element you want to access. The first array element is 0 and not 1 as you would
think and the last element is 1 less than the size of the array. Here is an example of how to set all 3 values
of an array and how to print them.

arr[0] = 5;

arr[1] = 12;

arr[2] = 7;

Console.WriteLine(arr[0]);

Console.WriteLine(arr[1]);

Console.WriteLine(arr[2]);

Arrays with loops

It is much easier to work with an array when you use a loop. Here is an example of how to print all the
values in an array of 10 elements using a for loop.

int[] arr = new int[10];

for (int x = 0; x < 10; x++)

Console.WriteLine(arr[x]);

You can go through all the elements in an array without having to specify how many of them there are by
using a foreach loop. In the following example the y is given the value of each element of the array for each
iteration of the loop.

foreach (int y in arr)

Console.WriteLine(y);

Multi-dimensional arrays

A multi-dimensional array is an array that has elements in more than one dimension. A 2-dimensional can
be thought of as having both an x and a y dimension. You do get arrays with more than 2 dimensions but
they are not used very often. Here is a table that will help you imagine what a 2-dimensional array looks
like.

0 1 2

01 2 3

14 5 6

27 8 9

When you declare a 2-dimensional array you must separate the dimensions with a comma. Here is an
example of how you would declare a 2-dimensional array with 3 elements as the size of each dimension.

int[,] arr2 = new int[3,3];

You also use a comma when setting the value.


arr2[1,2] = 5;

2 loops are needed when working with a 2-dimensional array. The one loop must be put inside the other.
Here is an example of how to print all the values of a 2-dimensional array.

for (int i = 0; i < 3; i++)

for (int j = 0; j < 3; j++)

Console.WriteLine(arr2[i,j]);

Learn C# Programming Tutorial Lesson 6 - Methods


When you want to repeat the same lines of code in many different parts of a program you should put that
code inside a method and just call the method as many times as you need to.

A method must be created outside other methods including the Main method. Here is an example of how
to create a method called PrintHello which will print hello on the screen. The whole program is included to
show you where the method must be created.

using System;

class methods

private static void PrintHello()

Console.WriteLine("Hello");

public static void Main()

PrintHello();

The private keyword means that the method can only be called from in the same class. If you used the
public keyword in its place then it would be accessible from anywhere. The static keyword must be used
because it is going to be called from the main method which is also static. This method has no return value
so void must be used. The name of the method follows the return value which in this case is PrintHello. All
methods must be followed by brackets. The contents of the method are put between the curly brackets
that follow it. Console.WriteLine is used inside the method to print Hello. The PrintHello method is called
from the Main method by using its name followed by brackets and a semi-colon to end the statement.

Parameters and return values

Variables can be passed to a method by putting them between the brackets that follow its name. Here is an
example of how you would pass 2 integers to a method called Add that adds the 2 values together.

static void Add(int n1, int n2)

int answer;

answer = n1 + n2;

You would call this method with the values in brackets.

Add(1,2);

We can use the return value of a method to get the answer. Changing void to int will make the method
return an integer. You need to use the return keyword at the end of the method to return the value.

static int Add(int n1, int n2)

int answer;

answer = n1 + n2;

return answer;

You can store the result from the method in a variable by setting the variable equal to the method when
calling it.

int total;

total = Add(1,2);

Reference parameters

The methods that we have done so far use pass by value parameters. This means that a copy of the
variable passed to the method is used instead of the actual variable. If you change the value of a parameter
passed by value it will not change the value of the variable in the method that called it. You must pass
parameters by reference by using the ref keyword if you want the variable in the calling method to be
changed.

The following example has a method called AddOne which takes an int as a parameter and adds 1 to that
value. Because it is a reference parameter the original value which in this case is x will have 1 added to it. It
is important to use the ref keyword in both the method that is called and the method that calls that
method. You also have to initialize the variable that is passed by reference to something before passing it.
using System;

class methods

private static void AddOne(ref int i)

i = i + 1;

public static void Main()

int x = 0;

AddOne(ref x);

Console.WriteLine(x);

Global and local variables

A global variable can be accessed by any method and a local variable can only be accessed by the method it
is declared in. When a variable is declared outside of all methods it becomes global. Here is an example
that shows that a local variable can only be accessed in its method and that a global variable can be
accessed from any method.

using System;

class methods

static int MyGlobalVariable;

static void ChangeGlobalValue()

int MyLocalVariable;

MyLocalVariable = 4;
MyGlobalVariable = 5;

public static void Main()

MyGlobalVariable = 7;

ChangeGlobalValue();

Learn C# Programming Tutorial Lesson 7 - Working with Strings


Strings are used when displaying messages to the user which happens in almost every program which
means that it is very important to understand them well. This lesson will show you some ways to work with
strings and how to make it easier to use them.

Methods built into the string data type

The string data type has many methods built into it. The ToUpper() and ToLower() methods for example
will change a string to upper case and lower case letters respectively.

string s = "Hello";

string upper = s.ToUpper();

Console.WriteLine(upper);

string lower = s.ToLower();

Console.WriteLine(lower);

The Length property of a string will tell you how many characters there are in a string.

string s = "Hello";

Console.WriteLine(s.Length);

The SubString() method is used to get a specific part of a string. It takes 2 parameters which are the
position to start at and the number of characters to copy. The following example extracts the word "Good"
from "Good Morning" by getting 4 characters starting at position 0.

string s = "Good Morning";

string t = s.Substring(0, 4);

Console.WriteLine(t);
The string type has many other methods. You can find out about them by reading about the string data
type in the C# documentation.

Converting to and from strings

Every object in C# has a ToString() method which will convert that object to a string. If you use the
ToString() method of an int you will get the value of that int as a string. Some other objects that can't be
converted directly to a string will return a value that best represents the object as a string.

int i = 5;

string s = i.ToString();

Console.WriteLine(s);

Whenever you ask a user to enter a number it will be read as a string. You will probably want to convert
the number to an int or double type. The int and double types both have a Parse() method for converting a
string to the correct data type. You must however use the int and double classes when calling the Parse()
method and not call it from the variable name.

string s = Console.ReadLine();

int i = int.Parse(s);

double d = double.Parse(s);

Escaping characters

In c# the \ character is used to escape special characters. If you want to put an enter character in a string
then you have to use \n because putting an enter in your code is obviously not practical. There are many
other special characters such as \t for tab. The following example will print Hello and then put in an enter
character and will put Good Morning on the next line with a tab between the 2 words.

string s = "Hello\nGood\tMorning";

Console.WriteLine(s);

Because the \ is used in this way it must also be escaped. This is done by simply using 2 of them next to
each other. You will be using the \ character a lot because it is used as a directory separator when working
with files.

string s = "C:\\Test";

Console.WriteLine(s);

If you don't want to have to escape characters all the time then you can use the @ sign in front of a string
to make it not escape any characters.

string s = @"C:\Test";

Console.WriteLine(s);

Strings as arrays of characters


A string is actually just an array of characters which means you can use square brackets like you would with
an array to access any character in a string. Here is an example of how to get the letter 'e' from the string
"Hello".

string s = "Hello";

char c = s[1];

Console.WriteLine(c);

Learn C# Programming Tutorial Lesson 8 - Classes and Objects


What is a class?

A class is basically a single module of a program. All C# programs other than the most basic ones use many
classes. Classes help to divide up a program into modules so that it is easier to work with the code.

Something you must understand about classes is that they are actually like an architect's plan for a house.
You don't usually use the code in a class directly but rather you create objects from a class and use the
objects. An object is like the house that is built from the architect's plan.

Creating a class

You have already used a class before when you created your first program. We are going to go one step
further now and create another class that is used by the main program. Here is an example of a class called
MyClass which you can create in a file called MyClass.cs:

using System;

class MyClass

It should look similar to the other programs you have written. You will see though that there are no
methods in this class yet. Let's now add a simple method that just adds 2 numbers together and returns
the result.

using System;

class MyClass

public int Add(int a, int b)

int result = a + b;
return result;

You will see that I have made the method public so that it can be accessed from other classes. If you want
to hide a method from other classes then you can use the private keyword.

You already know a little bit about local and global variables. We are now going to create a public global
variable called sum which will store the sum of the result of all calls to the Add method to demonstrate
how global variables work in classes.

using System;

class MyClass

public int sum;

public int Add(int a, int b)

int result = a + b;

sum = sum + result;

return result;

Using a class

When you create an object from a class we say that you are instantiating an object of that class. We are
now going to create the main program class, like you have done before in previous programs, which will
instantiate an instance of MyClass. Here is the code for the main program class which will be called
TestClass and will be saved in a file called TestClass.cs:

using System;

class TestClass

public static void Main()

{
}

Now we use the new keyword to instantiate an instance of MyClass from the main program. When you
instantiate a class you must give it a name just like when you declare a variable. This one will be called mc.

using System;

class TestClass

public static void Main()

MyClass mc = new MyClass();

Now we will use the Add method of MyClass to add the numbers 5 and 7 together and the numbers 3 and
2. We will then print out the 2 results as well as the sum from MyClass.

using System;

class TestClass

public static void Main()

MyClass mc = new MyClass();

int res1 = mc.Add(5, 7);

Console.WriteLine(res1);

int res2 = mc.Add(3, 2);

Console.WriteLine(res2);

Console.WriteLine(mc.sum);

When you run the program you should see the numbers 12, 5 and 17 each on their own line.
Constructors

A constructor is a method that runs when a class is instantiated and is used to initialize the state of the
object. A constructor looks very similar to any other method in a class except that it doesn't have a return
value. A constructor must also have the exact same name as the name of the class. Here is an example
using the MyClass example from above that initializes sum to 10:

using System;

class MyClass

public MyClass()

sum = 10;

public int sum;

public int Add(int a, int b)

int result = a + b;

sum = sum + result;

return result;

A constructor can have parameters just like a normal method. You can also overload a constructor. We will
now overload the MyClass constructor with another constructor that takes a parameter.

using System;

class MyClass

public MyClass()

{
sum = 10;

public MyClass(int s)

sum = s;

public int sum;

public int Add(int a, int b)

int result = a + b;

sum = sum + result;

return result;

To use a constructor that has parameters you must put the values to be passed as parameters in the
brackets after the class name when instantiating the class.

using System;

class TestClass

public static void Main()

MyClass mc = new MyClass(25);

Console.WriteLine(mc.sum);

}
Learn C# Programming Tutorial Lesson 9 - Inheritance, Abstract Classes
and Interfaces
Inheritance

Inheritance is the ability of classes to inherit things like methods and variables from another class. This
means that you can create one parent class that has a method in it and all the classes that inherit from the
parent class can use that method as if it belongs to them as well.

The best way to explain inheritance is with an example. First we will create a class called ParentClass which
has a method in it called SayHello() which prints "Hello" on the screen.

using System;

class ParentClass

public void SayHello()

Console.WriteLine("Hello");

Now we will create another class called ChildClass which will have no methods in it but it will inherit from
ParentClass. If you want to inherit from another class you must put a semi-colon after the child class name
and then put the name of the parent class to inherit from.

using System;

class ChildClass : ParentClass

Now we will create a small program that will test ChildClass. You will see that ChildClass has no methods.
Through the use of inheritance you can use the SayHello() method that is inherited from ParentClass. Here
is the test program:

using System;

class Program

{
static void Main(string[] args)

ChildClass cc = new ChildClass();

cc.SayHello();

Console.ReadLine();

When you run the program you will see that it prints Hello on the screen.

Abstract Classes

An abstract class is just like a normal class except that abstract classes can't be instantiated. You can only
inherit from an abstract class.

We will use the ParentClass example from above and change it to an abstract class. The only change you
have to make to ParentClass is to put the abstract keyword in front of the class declaration.

using System;

abstract class ParentClass

public void SayHello()

Console.WriteLine("Hello");

Interfaces

An interface is something that is used to make sure that a class implements a certain group of methods.
The methods in an interface do not have any code in them and are ended with a semi-colon instead of
having curly brackets. You also can't declare variables in an interface.

We will first create an interface called ITest with a method called SaySomething().

using System;

interface ITest

{
void SaySomething();

Next we will create 2 classes called Test1 and Test2. Both of them will implement the ITest interface. You
inherit from an interface in the same way as inheriting from a class which is to put it after a semi-colon
after the class name. Both classes will have a SaySomething() method but each will print something
different on the screen.

using System;

class Test1 : ITest

public void SaySomething()

Console.WriteLine("Hello");

using System;

class Test2 : ITest

public void SaySomething()

Console.WriteLine("Goodbye");

Finally we will need a test program. The test program declares an ITest. A new instance of Test1 is assigned
to the ITest and then the SaySomething() method is called on it. A new instance of Test2 is then assigned to
the ITest and then the SaySomething() method is called on that one. You will see that even though the
same method name is called, it prints something different each time. This is because the interface is using
something called polymorphism which allows a method to be called from any class as long as it has the
same name. Here is the test program.

using System;

class Program
{

static void Main(string[] args)

ITest it;

it = new Test1();

it.SaySomething();

it = new Test2();

it.SaySomething();

Console.ReadLine();

You might also like