Dana Vrajitoru
B583 Game Programming and Design

Introduction to C#

C#

Data Types

C# Classes

Classes in C#

public class Manager: GameObject { 
    public int level;
    public Manager() {
        level = 0;
    }
    ...
} 
Manager m = new Manager();

Structs

Example

public struct CoOrds { 
    public int x, y; 
    // cannot initialize them here 
    // unless they are static or in Unity
    public CoOrds(int p1, int p2) { 
        x = p1; 
        y = p2; 
    } 
} 

Arrays

Loops

foreach (int element in a1) {
    System.Console.WriteLine(element); 
} 
for (int i=0; i < a1.Length; i++) {
    element = a1[i];
    System.Console.WriteLine(element); 
} 

Exception Handling

Example

object o2 = null; 
try 
{ 
    int i2 = (int) o2; // Error 
}
catch (InvalidCastException e) { 
    // take some action
}

Function Parameters

Ref Example

class RefExample 
{
    static void Method(ref int i) { 
        i = i + 44; 
    } 
    static void Main() { 
        int val = 1; 
        Method(ref val); 
        Console.WriteLine(val); 
        // Output: 45 
    } 
}

Out Example

class OutExample {
    static
    void Method(out int i) { 
        i = 44; 
    } 
    static void Main() { 
        int val; 
        Method(out val); 
        Console.WriteLine(val); 
        // Output: 44 
    } 
}