C# Guides/Tutorials for everyone!

Since I for a longer time have seen very many asking for C# tutorials and seen many very simple questions I thought I would make a fast yet detailed guide about C#. Now don’t expect everything to be perfect and please correct me if there is times where I’m wrong, everybody should know that errors are possible. I’m thinking of releasing 1 or 2 maybe more guides a week depending on how much extra time I have to spare, and every guide will be edited into this thread, which mean that I will not always have posted a reply to let anyone know I’ve updated this thread. I’ll start out very basic so all those who have never programmed before can follow along. This guide will in the beginning not focus on unity but the C# language in general. If you wish to use unity as your “Environment” you may need to change some minor things up a bit; Eg: Console.WriteLine(“Hello”); Would be Debug.Log(“Hello”); In Unity. I will in this guide main focus on Console applications and Class libraries, where class libraries are the same thing unity3D is using.

Tutorial 0: Creating your solution

To follow along any tutorial create a new solution. If you have unity installed you’ll have mono development as standard, but you can use visual studio as well or any other IDE you prefer.
To create a new solution go to “File → New → Solution…” A window should pop up. Select C# → Console Project and give it a name. I’ll call mine Tutorial for now, but you can call it whatever you want, but you should be able to remember the name.
Click okay and you’re met with a simple Hello World Program!
Click Ctrl+F5 to compile and run, console window should pop and say “Hello World!”

Tutorial 1: Data Types

In this tutorial we will go in depth with data types and how to use them. We will also see how you can manipulate data type as well as their structure. This chapter is huge and very basic. We will in this chapter cover Data Type, Suffix, Conversions and Cast.

In C# we have different kinds of types. We have:
Built-in types: Directly supported by Common Type System (CTS) and
User-defined types: complex types composed of other types.
We additional have that those2 kind of types can be either:
A value type or
A reference type.
A value type is a type which have a value associated. We can for instance say I’m 1 and you are 2. Now imagine a study room where they use a number system to indicate who should speak, if the lector would ask you he would say “Number 2” and since you have the value 2 we know that it is you.
A reference type is a little more tricky. We can Explain a reference type as a “pointer”. Let say you have a reference type T and you assign this T as a “new” T to a variable A, then A will be the object which holds the reference. Let now say we have a variable B and we say B = A, then B will be a reference to A since A holds a reference type. This will make much more sense when we get to classes and instantiation, for now just think of a reference type as a variable that basically says “I’m the exactly same as….”
As a reference here is a list over type:
•Value types (primitive types):

  • Numeric types:
    • Positive integer (Z +): byte, ushort, uint, ulong
    • integer (Z): sbyte, short, int, long
    • Real numbers (R): float, double, decimal
  • Logical types: bool
  • Characters: char
    • Reference Types
  • string
  • object

Built-in Integer types and their range:

Type Size Range (Inclusive) Base Class Library (BCL) Name Signed
sbyte 8 bits -128 to 127 System.SByte Yes
byte 8 bits 0 to 255 System.Byte No
short 16 bits -32,768 to 32,767 System.Int16 Yes
ushort 16 bits -32,768 to 32,767 System.uInt16 No
int 32 bits –2,147,483,648 to 2,147,483,647 System.Int32 Yes
uint 32 bits 0 to 4,294,967,295 System.UInt32 No
long 64 bits –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 System.Int64 Yes
ulong 64 bits 0 to 18,446,744,073,709,551,615 System.UInt64 No

built-in comma-types

Type Size Range (Inclusive) Base Class Library (BCL) Name Significant Digits
float 32 bits ±1.5 × 10⁻⁴⁵ to ±3.4 × 10+38 ±1.5 × 10⁻⁴⁵ to ±3.4 × 10+38 System.Single 7
double 64 bits ±5.0 × 10−324 to ±1.7 × 10+308 System.Double 15-16
decimal 128 bits 1.0 × 10−28 to approximately 7.9 × 10+28 System.Decimal 28-29

Larger numbers less precision (rounding error) - scientific calculations. Smaller numbers, more precision (no rounding errors) - financial calculations. Eg; 1E9 = 1000000000

Numeric Suffix
Numeric Suffix is used to cast values to a curtain data type. Hardcoded values (literals) is interpreted as int (then uint, long, ulong) or double (depending on.) Suffix can be added to force the literal to a specific data type. Eg;

float f = 6.5; //Compile error use f
decimal m = 6.5; //Compile error use m
float f = 6.5f;
decimal m = 6.5m;

The suffixs can be found in the following table:

Suffix Type Numeric Suffix Suffix Example
unsigned int U or u uint x = 100U;
long L or l long x = 100L;
unsigned long UL or ul ulong x = 100UL;
float F or f float x = 100F;
double D or d double x = 100D;
decimal M or m decimal x = 100M;

Numeric Conversions
There is 2 types of conversions which is implicit and explicit
• Implicit is when the destination type can hold all values from the source type.
• Otherwise require explicit conversion (cast).

Quiz 1: What kind of cast is the following?

short s1 = 10;
int i1 = s1;
short s2 = (short)i1;


The image shows what implicit cast are possible.

Explicit conversion (cast)
Explicit conversion (cast) May result In loss of precision or OverflowException.
1 Real number → Integer: Decimal gets removed.
2 decimal → integer.

  • If the value is out of range: OverflowException
    3 double / float → integer:
  • If the value is out of range: OverflowException
    4 Double → float: Rounding
  • Value out of range: 0 or infinity.
    5 float / double → decimal conversion to decimal representation
  • Impairment small: 0
  • Value is NaN (not a number), infinity, or too large: OverflowException
    6 Decimal → float / double: Rounding to the nearest value

The bool type
bool or boolean can only be either true or false. In some other programming languages 0 usually represent false and everything else is true, however C# does NOT support this directly. In C# we can only have that a bool and be true, and false as boolean expression also only can work with true false, which we will see later. bool can’t be conversion to / from other types.

The char type
char or character can only contain a single Unicode characters - each character has unique number. To look up characters refer to: http://www.unicode.org/charts If that isn’t enough do a google search on “ascii tables”. chars can be converted to short.

Quiz 2: What does the following code print

char x1 = 'H'; // literal
char x2 = '\x0065'; // Hexadecimal
char x3 = (char)121; // Cast fra numerisk type 
char x4 = '\u0021'; // Unicode
Console.WriteLine (x1 + x2 + x3 + x4);

Table over Unicode escape characters:

Escape Sequence Character Name Unicode Encoding
\’ Single quote \u0027
\” Double quote \u0022
\ Backslash \u005C
\0 Null \u0000
\a Alert (system beep) \u0007
\b Backspace \u0008
\f Form feed \u000C
\n Newline \u000A
\r Carriage return \u0009
\v Vertical tab \u000B
\uxxxx Unicode character in hex \u0029 (example)

The string type
A string id represented by an array of char. String class has a rich API consisting of a load of methods. For full reference look up http://msdn.microsoft.com/en-us/library/system.string_members(v=vs.90).aspx An example of a string build up with char:

string s1 = new string(new char[] { 'H', 'e', 'l', 'l', 'o' });

Optional Exercise 1: Write a string only using Hexadecimals, Cast, and Unicode

Console in- and output
This is not available in unity but if you write a simple console application you can use them as following:

Input:

Console.Read(); //Read a unicode number
Console.ReadKey(); //Read a ConsoleKeyInfo
Console.Readline(); //Read a string

Output:

Console.Write(); //Write to the console.
Console.WriteLine(); //Write a line to the console.

Exercise 2: Write a program that ask for input and then print it!

Converting Between String and numeric types
You can convert a string type to a numeric type with Parse(). Parse () is defined for all numeric data types. TryParse () handles conversion errors by returning false instead of throwing an exception:

emergencyText string = "911";
int = emergencyNum int.Parse (emergencyText);
if (int.TryParse (emergencyText, out emergencyNumber))
{
    / / Converted Correctly, now use number
}

Enum
Enum is a way of numerate items. Usually enum items are numerated in the following way: 1, 2, 4, 8, 16, 32…

enum Weekday { Mon, Tue, Wed, Thu, Fri, Sat, Sun };

You can change the values as you desire as seen below, and you can also limit the numbers to any numeric type. Below we see an example of using a ushort limitation.

public enum StatusCode : ushort { OK = 200, Created, Accepted, NotFound = 404 };

Another example is to numerate the from 0, 1, 2… n which we see here:

public enum Numbers { zero = 0, one = 1, two = 2 };

The ?? Operator
The ?? operator is called the null-coalescing operator and is used to define a default value for nullable value types or reference types. It returns the left-hand operand if the operand is not null; otherwise it returns the right operand. For code example see below:

// y = x, unless x is null, in which case y = -1. 
int y = x ?? -1;

Quiz 1 Answer:
Implicit
Implicit
Explicit

Quiz 2 Answer:
“Hey!”

Exercise 2 Answer:

Console.Write("Enter your name: ");
string s = Console.ReadLine();
Console.WriteLine ("Hello " + s + "!");

Tutorial 2: Data Structure (Arrays and Lists)

In this tutorial we will look at data structures. A data structure (aka collection classes) contains a collection of items. For now we will only look into two kind of data structures; Arrays (fixed size data structure) and List (variable size data structure) Using System.Linq. The System.Collections.Generic namespace also In addition contains data structures like Dictionary, LinkedList, Stack, Queue, … and many more which can be seen here: System.Collections.Generic Namespace | Microsoft Learn .

First of we will see on fixed arrays. Arrays must at any time have a size declared upon creating the array. If you have an array of size 3 will be able to put 3 item into the 3 spaces availble, however the indexing in a array starts from 0 to the array size – 1, in other words if you have an array of size 3 the index start from 0 and end at 2, as will will see in the following example.

//1. Declaration followed by initialization
string[] languages; 
languages = new string[3]; //default: 0, ‘\0’, null,false
languages[0] = "C#";
languages[1] = "Java";
languages[2] = "Ruby"; 
languages[3] = "Illegal"; //IndexOutOfRangeException
//2. Other initialization methods:
string[] languages2 = new string[]{"C#", "Java", "Ruby"}; 
string[] languages3 = {"C#", "Java", "Ruby"};

Additional we also have that arrays can be multidimensional which basically means the array have more than one “axis” eg; 2D arrays would have 2 axis, X and Y, 3D arrays would have 3 axis X, Y, Z, and so on. Example of 2D arrays can be found below:

int [,] numbers = new int [3,3];
int num = 1;
for (int i = 0; i < numbers.GetLength (0); i++)
   for (int j = 0; j < numbers.GetLength (1); j++)
      numbers [i, j] = num + +;

// Initialization of 2-dimensional array using array initializer
int [,] numbers = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
Jagged arrays (arrays of arrays)
int [] [] numbersjagged = new int [] []
{
   new int [] {1, 2},
   new int [] {3, 4, 5},
   new int [] {6, 7, 8, 9}
};
// rectangular array access
numbers [0, 0] // 1
numbers [2, 2] // 9
// jagged array access
numbersjagged[0][0] // 1
numbersjagged[2][3] // 9

List collection class
List is Used for variable collection size. It is implemented internally as an array that can grow when the capacity is reached. There are many kinds of list type as mentioned in the first paragraph of this chapter, which all works a little different. List is not only flexible, it’s also fast with a running time of O(n) for searching and O(1) for indexed inserting and O(n) for searching and sorting. For full reference of the List refer to: List<T> Class (System.Collections.Generic) | Microsoft Learn . Some examples of using a List can be seen below:

List<string> languages = new List<string>(); 
languages.Add("C#"); 
languages.Add("Java"); //{C#,Java}
languages.AddRange( new List<String>() {"Ruby", "Scala"});//nu {C#,Java, Ruby,
Scala}
languages.Insert(1, "Python"); //{C#, Python,Java, Ruby, Scala}
languages.InsertRange(1, new string[]{"F#", "Haskell"}); //nu {C#, F#,Haskell,
Python,Java, Ruby, Scala}
languages.Remove("Haskell"); //nu {C#, F#, Python,Java, Ruby, Scala}
languages.RemoveAt(1); //nu {C#, Python,Java, Ruby, Scala}
languages.RemoveRange(2, 2); //nu {C#, Python, Scala}
languages[1] = "Iron Python"; //nu { C#, Iron Python, Scala }
Console.WriteLine(languages.Count); // 3
Console.WriteLine(languages[5]); //IndexOutOfRangeException

Quiz 1: Which elements does the list contains after each step?

List<int> numbers = new List<int>();
numbers.Add(1);
numbers.Add(2);
numbers.AddRange(new List<int>() { 3, 4 });
numbers.Insert(1, 5);
numbers.InsertRange(1, new int[] { 6, 7 });
numbers.Remove(3);
numbers.RemoveAt(1);
numbers.RemoveRange(2, 2);
numbers[1] = 8;
Console.WriteLine(numbers.Count);
Console.WriteLine(numbers[5]);

Quiz Answer 1:

List<int> numbers = new List<int>();
numbers.Add(1); //1
numbers.Add(2); //1, 2
numbers.AddRange(new List<int>() { 3, 4 }); //1, 2, 3, 4
numbers.Insert(1, 5); //1, 5, 3, 4
numbers.InsertRange(1, new int[] { 6, 7 }); //1, 6, 7, 5, 2, 3, 4
numbers.Remove(3); //1, 6, 7, 5, 2, 4
numbers.RemoveAt(1); //1, 7, 5, 2, 4
numbers.RemoveRange(2, 2); //1, 7, 4
numbers[1] = 8; //1, 8, 4
Console.WriteLine(numbers.Count); //3
Console.WriteLine(numbers[5]); //IndexOutOfRangeException

Tutorial 3: Boolean Expressions

In this chapter we will look into boolean expression and logical expression. When speaking about boolean expression we have the following:

Name Operator Logically name
Equal == EQU
Not Equal != NEQ
Less than < LSS
Greater than > GTR
Less or equal <= LEQ
Greater or equal >= GEQ

The operator is used to determine whether something is true or false. It is mainly used in if statements and loop statement like this: “if(var1 == var2)”. It may as well be used for variable declaration by using the “?” sign, which is basically the same as an if statement, like this: “bool b = (var1 == var2) ? false : true” if var1 == var2 b will be true but otherwise false.

Quiz 1: Consider the following boolean expression and answer whether they’re true or false:
1 == 6
7 < -7
5 <= 5
1 > 4
5 != 5

Optional Quiz 2: For all the operators above write the logically name.
Optional Quiz 3: Write the boolean expression from quiz 1 inside a Console write line, what happens?
Optional Quiz 4: Declare a string a value by using the “?” operator.

Logical expression

Logical expressions contains of 4 simple expressions which is OR, AND, NOT, and XOR. There is additional also NAND, NOR, NXOR, but those are not available as a single operator but is a combination of NOT and AND for instance. In the table below you can see examples of the usage:

Name Operator Truth Table
And


AND
False
True


False
False
False


True
False
True


Or
XOR ^


XOR
False
True


False
False
True


True
True
False


NOT !


NOT
False
True



True
False


Quiz 5: Consider the boolean expressions below and determine whether it is true or false
(True !False) || False
(False || !True) ^ True
(False ^ False) True
(True ^ False) !True
(True ^ !True) (True || False)

Quiz 6: Rewrite the following code into only using one if statement

			if(true || false)
			{
				if(true ^ false)
				{
					if(true  true)
					{
						Console.WriteLine("Done stuff");
					}
					if(true ^ false)
					{
						Console.WriteLine("Done stuff");
					}
				}
				if(!false  true)
				{
					if(!false || false)
					{
						Console.WriteLine("Done stuff");
					}
				}
			}

Optional Quiz 7: Rewrite all the boolean expression in Quiz 5 into if statements.

When you have to do different things depending on the value you evaluate in an if statement you’ll have to use additional if cases, however in some cases you want to only do one of those things, and in that case you will need to use else if and else. If you want max performance you should have the most common thing in top, eg. Let say the most common thing in a int is 0

			if (i == 0)
			{
				//i is 0
			}
			else if (i == 1)
			{
				//i is 1
			}
			else if (i == 2)
			{
				//i is 2
			}
			else if (i == 3)
			{
				//i is 3
			}
			else
			{
				//Everything else
			}

The above example show how to make an if, else if, and else case but the above can actually be rewritten into a switch case. Switch cases can only be used as an alternative if you only use the EQU/== operator and only check one thing in each case. An example is shown below and is completely equivalent to the above example.

			int i = 0;
			switch(i)
			{
				case 0:
				{
					//i is 0
				}
				case 1:
				{
					//i is 1
				}
				case 2:
				{
					//i is 2
				}
				case 3:
				{
					//i is 3
				}
				default:
				{
					//Everything else
				}
			}

If we for instance had an if statement like this “if (i == 0 || i = 1)” we couldn’t make into a single switch case.

Quiz 1 Answer:
False
False
True
False
False

Quiz 2: Answer:
EQU
LSS
LEQ
GTR
NEQ

Quiz 3 Answer:
It write a boolean value depending on whether the expression is true or false.

Quiz 4 Answer:
Example:

string s = (var1 == var2) ? "false" : "true";

Quiz 5 Answer:
True
False
False
False
True

Quiz 6 Answer:

			if((true || false)  ((true ^ false)  ((true  true) || (true ^ false))) || ((!false  true)  (!false || false)))
			{
				Console.WriteLine("Done stuff");
			}

Tutorial 4: Loop Types

This chapter is short and will focus on the 4 loops we have in C#. The 4 types can be seen in the table below:

Loop Name Code sample Eveluation
While while(Bool Expression)
{
//Body
}
Run as long the Bool Expresion is true.
Do while
do
{
//Body
}
while(Bool Expresion)
Always run once and then as long the Bool Expresion is true.
For for(variable; Bool Expression; Expression)
{
//Body
}
Creates and/or assign the variable, then see if the Bool Expression is true and run the body and then do the expression and then see if the Bool Expression is true and so on…
foreach
foreach(type T in datastructure)
{
//Body
}
Loops through a datascruture/collection and only stop when all items have been looped over.

Additional you can use the break and continue keywords inside a loop. The break keyword breaks the loop and jump out if the loop and run the code after the loop, where continue ignore all code in the loop and jumps back up and evaluate the boolean expression in the loop.

Exercise 1: Write a while loop with boolean expression (int < 10) and write to the console the int only when it is larger than 5.
Exercise 2: Write a for loop which breaks after 5 interations.

Exercise 1 Answer:

			int i = 0;
			while (i < 10)
			{
				i++;
				if (i < 5)
					continue;
				Console.WriteLine(i);
			}

Exercise 2 Answer:

			for (int i = 0; i < 10; i++)
			{
				if(i > 5)
				{
					break;
				}
				Console.WriteLine(i);
				
			}

Tutorial 5: Methods

Method Declaration
A method declared inside a class or struct in the form: [Access Modifier][Method Modifier][return-type]name([parameters])
There are 4 access modifiers: public, private, protected, internal, and there is 4 Method Modifier: abstract, override, static, virtual you can read up on them all and few others here: http://msdn.microsoft.com/en-us/library/6tcf2h8w(v=vs.71).aspx but for now we will focus on static. Static class-method is called Class.Methode () where non-static is called from a variable var.Method(). The return types contains of: void, built-in types or user-defined types. A method can as standard only have a single return-type but there is way to manipulate this which we will work with later.

Parameter mechanisms
C # has three different parameter mechanisms:

  • Pass by value (the value parameter)
  • Pass by reference (with reference parameter)
  • Pass by reference (with output parameter)
    Parameters mechanisms determines how the parameters to a method of treatment. Pass by reference mechanisms permitting “returning” more than one value from a method.

Pass by Value with value parameters
This is the default parameter mechanism. The value of actual parameter is copied to the formal parameter. The purpose of this is to send parameters into the method. Example:

//callsite
static void Main(String[] args)
{
   int x = 5;
   MethodA(x); 
   //x = 5
   string name = "Ib"; 
   MethodB(name);
   //name = "Ib";
}

static void MethodA(int a)
{
   a += 10;
}

static void MethodB(string n)
{
   n += " Kong ";
}

Reference parameters (ref)
Parameter mechanism can explicitly be changed to pass by reference. ref indicates that the formal parameter is the alias of the current parameter (not a copy). The purpose is to send parameters in and out of the method. Example:

//callsite
static Main()
{
   int x = 5;
   MethodA(ref x); 
   //x = 15
   string name = "Ib"; 
   MethodB(ref name);
   //name = "Ib Kong"
}

static void MethodA(ref int a)
{
   a += 10;
}

static void MethodB(ref string n)
{
   n += "Kong ";
}

Output parameters (out)
As a ref, however it does not need the current parameters to be initialized by the call. Formal parameters must be initialized before the return to the call site. The purpose is to send parameters out of a method

//callsite
static Main()
{
   int x;
   MethodA(out x);
   //x = 10
   string name = "Ib"; 
   MethodB(out name); 
   //name = ”Ib Kong”
}

static void MethodA(out int a)
{
   a = 10;
}

static void MethodB(out string n)
{
   n += "Kong";
}

Parameter arrays
params modifier can be used as the last parameter in a method Specifies that the method accepts any numbers of parameters of a given type (an array can also be used). Parameter type must be declared as an array. Example:

static Main()
{
   int total0 = Sum();
   int total1 = Sum(1, 2, 3, 4);
   int total2 = Sum(new int[] { 1, 2, 3, 4 });
}

static int Sum(params int[] numbers)
{
   Int sum = 0;
   for (int i = 0; i < numbers.Length; i++)
      sum += numbers[i];
   return sum;
}

Method Overloading
Method Overloading is a way to have different ways to call a method. We set up multiple methods with the same name but different signature (number and / or type of parameters). This makes it possible to implement logic into one method that the other overloaded methods call (easy maintenance). Example:

class Program
{
   enum Sex
   { 
      Male, Female
   }

   static string Title(string name)
   {
      return Title(name, Sex.Male, 10, false);
   }

   static string Title(string name, Sex s)
   {
      return Title(name, s, 10, false);
   }

   static string Title(string name, Sex s, int age)
   { 
      return Title(name, s, age, false);
   }

   static string Title(string name, Sex, int age, bool married)
   {
      string prefix;
      if (s == Sex.Male) prefix = "Mr. ";
      else if (married) prefix = "Mrs. ";
      else prefix = "Ms. ";
      return prefix + name + ", age " + age +
      (married ? ", married" : "not married");
   }

   static void Main(string[] args)
   {
      string a = Title("Mox"); //”Mr. Mox, age 10, not married”
      string b = Title("Bee", Sex.Female); //”Ms. Bee, age 10, not married”
      string c = Title("T", Sex.Male, 50, true); //”Mr. T, age 50, married”
   }
}

Optional parameters
Optional parameters is an alternative to normal method overload. An optional parameter specifies a default value to a parameter. An optional parameter is optional in method calls and declares the specified default values. Default value shall be determined on compile time (so method calls can’t be used).
Ordering: [required parameters] optional parameters [, params *]
Let’s revisit our last example; instead of having 5 methods you can remake it into a single method like this:

static string Title(string name, Sex s = Sex.Male, int age = 10, bool married = false)
{
   string prefix;
   if (s == Sex.Male) prefix = "Mr. ";
   else if (married) prefix = "Mrs. ";
   else prefix = "Ms. ";
   return prefix + name + ", age " + age + (married ? ", married" : "not married");
}

Named parameters
Named parameters is identification of arguments by name instead of position. Named parameters can appear in any order. Positional and named parameters can be mixed but positional must be first (otherwise the compiler can’t determine parameter). One big disadvantage is that parameter names will be part of the API. Examples:

string Title(string name, Sex s = Sex.Male, int age = 10, bool married = false)
{
   return prefix + name + ", age " + age + (married ? ", married" : "not married");
}
string a = Title("Mox", age: 36);
string b = Title(age:36, name:"Mox");
string c = Title("T", Sex.Male, married:false, age:50);
string c = Title("Error", age:30, 29); //compile-time fejl (positionel efter navngiven)

Now since I haven’t made any exercises you should try to practice the concepts we walked over in this tutorial!

Tutorial 6: Exception Handling

Exception handling is a way of handling possible exceptions that may occur doing your program(s) runtime. An exception is thrown (throw) when a (serious) errors is not handled. You can catch an exception using a
try … catch … finally blocks. either catch or finally most be represented. In other words you do not need both a catch and finally block, but only one of them, the other one is optional. (Refer to code example below). Catch blocks must be classified by most specific exception first. System.Exception is at least specific and should appear last.

static void Main (string [] args)
{
   try
   {
      // can provide FormatException
      int a = int.Parse (Console.ReadLine ());
      int b = int.Parse (Console.ReadLine ());
      // can provide DivideByZeroException
      double c = (double) a / b;
   }
   catch (FormatException formatterror)
   {
      Console.WriteLine (formatError.Message);
   }
   catch (DivideByZeroException zeroDivideError)
   {
      Console.WriteLine ("You can’t divide by 0");
   }
   Catch (Exception Ex)
   {
      Console.WriteLine (Ex.ToString());
   }
   finally
   {
      Console.WriteLine ("We always get passed here lastly when everything else have been resolved");
   }
}

The “catch” block ONLY executes if we have a particular exception (which is specified in the catch block). Block “finally” executes ALWAYS, even if we don’t have any exceptions or errors. It also executes EVEN if we do “exit” or “return” in the “try” block.

Tutorial 7: Classes and Objects

In this chapter we will really start to dive into the object orientated programming manifesto. Object orientated programming builds on encapsulation, inheritance and polymorphism(in later tutorial) to structure systems. We will in this chapter have our focus on classes. Classes are our building block which is a template objects (instances of the class). A class is a data type that you can manipulate.
Everything is objects and therefore, there is a class for everything. The class specifies properties and behavior of objects of the class. Each object has a unique instance of the class, and is located in any given point in a particular state.
Objects can inherit properties and behaviors of other objects, have relationships, and can consist of other objects.
A class definition (class) indicates a new data type. A class consists of data and methods (members) which can either be attached to a body or to the class itself.
An example of a class is seen below as well as how to access it.

public class Person //Class difinition
{
    public string name; //fields
    public double height;
    public double weight;
    public double Bmi() //Method
    {
        return weight / Math.Pow(height, 2);
    }
}

class Program
{
    static void Main(string[] args)
    {
        Person kim = new Person();
        kim.name = "Kim";
        kim.height = 1.65;
        kim.weight = 67;
        Console.WriteLine(kim.Bmi());
        Person peter = new Person();
        peter.name = "Peter";
        peter.height = 1.82;
        peter.weight = 95;
        Console.WriteLine(peter.Bmi());
        Console.ReadLine();
    }
}

Optional Exercise 1: Use the Person class to make an object that symbolizes yourself, and print you bmi.

Instantiation and Constructors
Instantiation mean Creating instances (objects) of a class. Constructor is a special method that is called when an instance is created with the new operator. Constructor is used to initialize instance variables. this keyword is used to explicitly specify the instance member. A default constructor is automatically added unless explicitly add a constructor yourself. If you have added a constructor the default constructor will no longer be available. Let’s add a constructor to our Person class.

public class Person //Class difinition
{
    public string name; //fields
    public double height;
    public double weight;

    public Person(string name) //Contructor
    {
        this.name = name;
    }

    public double Bmi() //Method
    {
        return weight / Math.Pow(height, 2);
    }
}

If you have the program class in your project you will noticed that you’re now getting errors, this is because the default is no longer available. But we can simply add the default constructor simple by adding this code: “public Person(){ }” since it is possible to have multiple constructors.
You can use multiple constructors and constructor chaining to avoid redundancy. An example of constructer chaining can be seen below

    public Person()
        : this("N/A", 50, 1.50)
    { }
    public Person(string name)
        : this(name, 50, 1.50)
    { }
    public Person(string name, double weight)
        : this(name, weight, 1.50)
    { }
    public Person(string name, double weight, double height)
    {
        this.name = name;
        this.weight = weight;
        this.height = height;
    }

Exercise 2: Remove name and the constructors from the person class. Add 2 new fields called “First name” and “Last name”. Make a 3 Constructors or Constructor chain accepting First name and Last name, and one only accepting weight and height, and one that accepts all.

Exercise 2 Answer:

public class Person //Class difinition
{

    public string firstname; //fields
    public string lastname; //fields
    public double height;
    public double weight;

    public double Bmi() //Method
    {
        return weight / Math.Pow(height, 2);
    }

    public Person(string firstname, string lastname)
        : this(firstname, lastname, 50, 1.50)
    { }
    public Person(double weight, double height)
        : this("N/A", "N/A", weight, height)
    { }
    public Person(string firstname, string lastname, double weight, double height)
    {
        this.firstname = firstname;
        this.lastname = lastname;
        this.weight = weight;
        this.height = height;
    }
}

class Program
{
    static void Main(string[] args)
    {
        Person kim = new Person("kim", "Kimson");
        Console.WriteLine(kim.Bmi());
        Person peter = new Person("Peter", "Griffin", 150, 1.6);
        Console.WriteLine(peter.Bmi());
        Person unknown = new Person(50, 1.4);
        Console.WriteLine(unknown.Bmi());
        Console.ReadLine();
    }
}

Tutorial 8: Encapsulation

Coming next!

Tutorial 9: Inheritance

Coming Next week!

Credits and Thanks:

Maklaud - For correcting a few things that was poorly explained!

Recommendations:

Book: C# Essentials - Great book for beginner remember we used it in a programming coarse.
Video Tutorial: http://www.youtube.com/user/thenewboston - He have a good C# tutorial
Video Tutorial: http://www.youtube.com/user/kudvenkat - Have many good tutorial as well.
Homepage: http://www.csharp-station.com/Tutorial.aspx Many Good guides and tutorials including Exercises

This is amazing! great for people learning to script. I will be sure to send everyone a link to this page when they are looking for scripting tutorials! Nice job. I read a lot but not all since I know most of the things. I did actually learn some stuff that I did not know. Thanks

Thank you very much for your kind words ExpiredIndexCard, I just updated with 3 more tutorials, DAMN loads of stuff i wrote today! Hope everyone will enjoy :slight_smile:

Added Methods and Exception handling! Please let me know if there is any specific tutorial wishes and what you think of the tutorial! Hope you all enjoy! :smile:

Thanks! This is the best c# thread :slight_smile:

Not sure if its suitable for this thread, but i’d be interested on how to get started on making your (basic) item or monster class (c#)…

as in, I guess you could have baseEntity class(?), which has the main parameters that everything else inherits, name, price, size…
then you could have maybe swords class(?) or would these by types in the main class already(?)
with special sword related parameters/methods… And same for monsters…

thanks again!

@mgear, Thanks for the suggestion! The next tutorial will focus on classes and inheritances which is the building stones for such system, with some luck I’ll be able to have that tutorial up later or by tomorrow :smile:

Are you kidding? There are lots of books about C#, including different ones for dummies… I don’t think that Unity forum should teach people how to code using C# or JS. Using this way somebody may want to teach how to speak English, Russian, how to write topics etc…

Sure things, not because it’s in some degree is teaching to answer others question… Now I honestly disagree fully with you opinion, and I don’t wanna argue or start some huge angry fight about it so allow me to explain…

I know that there is loads of tutorials and such on the internet, but it seems that most people does not know this or look good enough for them. Lately I’ve seen a lot of people asking for very simple questions and C# references/advise and I’ve noticed that unity didn’t have any good resource thread for C# so I though I would make one so people could simply refer to it so people can get the necessary knowledge. This thread is far from perfect, if you really want in depth in sight in C# you should indeed buy a book, but this is an easy and free alternative that people can get started with, and I decided to make more out of it than just a reference thread but a more in depth tutorials that people can read and get basic knowledge. All that I write in this thread is something I write for free and educational purpose, and free knowledge is a good thing. I’m thinking of additional add a “further reading” section as well with books I can recommend!

Sorry, I didn’t want to start any fight, really :slight_smile: Just my opinion. If you think this thread is useful, keep it up. I just think people ought to visit some programming forums to learn C# or some blogs, e.g. MSDN. If they don’t want to do that, they may read it here…

Well I can’t say if it is useful, only the readers can, but I feel i cover the most necessary and still in a speed that allows people that haven’t touched much programming before to follow along, and I bet some guys and girls out there can find this useful and I hope for some both critique and positive feedback. The section may be a little wrong, maybe it would be better suited in… teaching or somewhere else but my hope is still some will find this useful which a few comments seems to state this is :slight_smile: - As said, I know you can easily find all this on the internet but some either don’t look around good enough or prefer to have everything at one place.

Ok, let me help you then a bit…

0 usually represent false and everything else is true.
It was in C++ and JavaScript. But in C# there are only true and false. You can’t make a condition like this:

if (numberOfItems)

You must write instead:

if (numberOfItems > 0)

Enum is a way of numerate items. Usually enum items are numerated in the following way: 1, 2, 4, 8, 16, 32…
It isn’t quite so. Sometimes they do that. But enums have values 0, 1, 2 etc. I mean the first value within enum is 0, the second is 1 etc. if we don’t assign other values.

The ?? operator is called the null-coalescing operator
Then don’t forget to tell about this one - ?: If condition on the left of the ? is true then operand between ? and : is used, otherwise operand to the right of the : is used.

Example:

bool readyToCreate = true;
int number = readyToCreate ? 10 : 0;

Oh, sorry, now I see you have told about it, but only like a “?” operator, it isn’t quite so.

catch (FormatException format terror)
Just a misprint “formatError”.

You can catch an exception using a try … catch … finally blocks
It’s possible to use only one of them - catch or finally:

try
{
}
catch (Exception e)
{
}

try
{
}
finally
{
}

Block “catch” executes ONLY if we have a particular exception (which is specified in the catch block). Block “finally” executes ALWAYS, even if we don’t have any exceptions or errors. It also executes EVEN if we do “exit” or “return” in the “try” block.

private void TryFinallyBlock()
{
try
{
return;
}
finally
{
Console.WriteLine("It will be printed!");
}
}

Not useful for me but good job!

Please teach me the basics of javascript because i am making an fps zombie game and i would like to make the scripts on my own please somebody help me and reply fast. Also i need unity’s javascript basics not some kind of super hard one because i literaly didnt understand anything of what jackie0100 said :frowning: please help fast.

Gab Steve, first, look at the topic’s name. It’s about c#, not JavaScript!
Second, stop being this. Don’t think somebody will teach you something RIGHT immediately. It’s just impossible. Go to some web-sites and learn JS basics, or by a book and read it. Everything depends on you only, if you don’t want to work hard, nobody can teach you.

yeah sorry :expressionless: