Keywords Keywords are predefined reserved words with special syntactic meaning. The language has two types of keyword — contextual and reserved. The reserved keywords such as false or byte may only be used as keywords. The contextual keywords such as where or from are only treated as keywords in certain situations.[1] If an identifier is needed which would be the same as a reserved keyword, it may be prefixed by the @ character to distinguish it. This facilitates reuse of .NET code written in other languages.[2] Using a keyword as an identifier: string @int; // @int is an ordinary string identifier, distinct from the 'int' keyword, // which retains its special meaning VALUE TYPES Pre-defined (primitive) datatypes – (Note: all are Value types / implemented as a struct) Operators Overloadable Operators Operators +, -, !, ~, ++, --, true, false Unary operators +, -, *, /, %, &, |, ^, <<, >> Binary operators == , != , <, >, <= , >= Comparison operators, must be overloaded in pairs Operator overloading Some of the existing operators can be overloaded by writing an overload method. public static Foo operator+(Foo foo, Bar bar) { return new Foo(foo.Value + bar.Value); } VALUE TYPES (Cont’d) An array in C# is what would be called a dynamic array in C++. Structures int[] numbers = new int[2]; Structures are more commonly known as structs. Structs are user-defined value numbers[0] = 2; types that are declared using the struct keyword. They are very similar to classes but are more suitable for lightweight types. Some important syntactical differences between a class and a struct are presented later in this article. struct Foo numbers[1] = 5; int x = numbers[0]; Initializers Array initializers provide convenient syntax for initialization of arrays. { // Long syntax ... int[] numbers = new int[5]{ 20, 1, 42, 15, 34 }; } // Short syntax Enumerations int[] numbers2 = { 20, 1, 42, 15, 34 }; Enumerated types (enums) are named values representing integer values. // Inferred syntax var numbers3 = new[] { 20, 1, 42, 15, 34 }; enum Season Multi-dimensional arrays { Winter = 0, Arrays can have more than one dimension, for example 2 dimensions to Spring = 1, represent a grid. Summer = 2, int[,] numbers = new int[3, 3]; Autumn = 3, Fall = Autumn // Autumn is called Fall in American numbers[1,2] = 2; English. } int[,] numbers2 = new int[3, 3] { {2, 3, 2}, {1, 2, 6}, {2, 4, 5} }; enum variables are initialized by default to zero. They can be assigned or initialized to the named values defined by the enumeration type. Season season; season = Season.Spring; REFERENCE TYPES Arrays An array type is a reference type that refers to a space containing one or more elements of a certain type. All array types derive from a common base class, System.Array. Each element is referenced by its index just like in C++ and Java. Classes (see the Classes section further down) Conditional Structures do ... while loop do if statement { Simple one-line statement: if (i == 3) ... ; ... // execute single statement if true } while (i == true); Multi-line with else-block (without any bra for loop[edit] ces): if (i == 2) ... else The for loop consists of three parts: declaration, condition and increment. Any of them can be left out as they are optional. for (int i = 0; i < 10; i++) ... { ... Recommended coding conventions for an if-statement. if (i == 3) { ... } Is equivalent to this code represented with a while statement. int i = 0; } while (i < 10) else if (i == 2) { { //... ... } i++; } else foreach loop { ... } The foreach statement is derived from the for statement and makes use of a certain pattern described in C#'s language specification in order to obtain and use an enumerator of elements to iterate over. Iteration structures Each item in the given collection will be returned and reachable in the context of Iteration statements are statements that are repeatedly executed when a given condition is evaluated as true. the code block. When the block has been executed the next item will be returned until there are no items remaining. while loop foreach (int i in intList) while (i == true) { { ... ... } } class Foo break statement { The break statement breaks out of the closest loop or switch statement. // Member declarations Execution continues in the statement after the terminated statement, if any. } int e = 10; Partial class This is a feature of C# 2.0. A partial class is a class declaration whose code is divided into separate files. The different parts of a partial class must be marked with keyword partial. for (int i = 0; i < e; i++) { while (true) // File1.cs { partial class Foo break; { } // Will break to this point. } continue statement ... } // File2.cs The continue statement discontinues the current iteration of the current control partial class Foo { statement and begins the next iteration. ... int ch; } while ((ch = Console.Read()) != -1) { if (ch == ' ') continue; Before you can use the members of the class you need to initialize the variable // Skips the rest of the while-loop // Rest of the while-loop ... } The while loop in the code above reads characters by calling GetChar(), skipping the statements in the body of the loop if the characters are spaces. Classes Declaration Initialization with a reference to an object. To create it you call the appropriate constructor using the new keyword. It has the same name as the class. Foo foo = new Foo(); For structs it is optional to explicitly call a constructor because the default one is called automatically. You just need to declare it and it gets initialized with standard values. Object initializers This is a feature of C# 3.0. Provides a more convenient way of initializing public fields and properties of an object. Constructor calls are optional when there is a default constructor. Person person = new Person { A class is declared like this: Name = "John Doe", Age = 39 Destructor }; The destructor is called when the object is being collected by the garbage // Equal to collector to perform some manual clean-up. There is a default destructor method Person person = new Person(); called finalize that can be overridden by declaring your own. person.Name = "John Doe"; person.Age = 39; Accessing members The syntax is similar to the one of constructors. The difference is that the name is preceded by a ~ and it cannot contain any parameters. There cannot be more than one destructor. Members of an instance and static members of a class are accessed using class Foo the . operator. { ... Accessing an instance member Instance members can be accessed through the name of a variable. ~Foo() string foo = "Hello"; { string fooUpper = foo.ToUpper(); Accessing a static class member ... } } Static members are accessed by using the name of the class or other type. int r = String.Compare(foo, fooUpper); Finalizers are always private. Methods Constructors Like in C and C++ there are functions that group reusable code. The main A constructor is a special method that is called automatically when an object is difference is that functions just like in Java have to reside inside of a class. A created. Its purpose is to initialize the members of the object. Constructors have function is therefore called a method. A method has a return value, a name and the same name as the class and do not return anything. They may take usually some parameters initialized when it is called with some arguments. It can parameters like any other method. either belong to an instance of a class or be a static member. class Foo class Foo { { Foo() int Bar(int a, int b) { { return a%b; ... } } } Constructors can be public, private, or internal. } A method is called using . notation on a specific variable, or as in the case of static methods, the name of a type. Foo foo = new Foo(); void Increment(ref int x, int dx = 1) { x += dx; } int r = foo.Bar(7, 2) int x = 0; Console.WriteLine(r); Increment(ref x); // dx takes the default value of 1 Increment(ref x, 2); // dx takes the value 2 ref and out parameters One can explicitly make arguments be passed by reference when calling a extern method with parameters preceded by keywords ref or out. These managed A feature of C# is the ability to call native code. A method signature is simply pointers come in handy when passing variables that you want to be modified declared without a body and is marked as extern. The DllImport attribute inside the method by reference. The main difference between the two is that also needs to be added to reference the desired DLL file. an out parameter must have been assigned within the method by the time the method returns, while ref need not assign a value. [DllImport("win32.dll")] static extern double Pow(double a, double b); void PassRef(ref int x) { if(x == 2) x = 10; Fields } Fields, or class variables, can be declared inside the class body to store data. int Z; class Foo PassRef(ref Z); { double foo; void PassOut(out int x) } { x = 2; Fields can be initialized directly when declared (unless declared in struct). } class Foo int Q; { PassOut(out Q); double foo = 2.3; } Optional parameters This is a feature of C# 4.0. Modifiers for fields: C# 4.0 introduces optional parameters with default values as seen in C++. For example: const - Makes the field a constant. private - Makes the field private (default). protected - Makes the field protected. The default modifiers for the accessors are inherited from the property. Note that public - Makes the field public. the accessor's modifiers can only be equal or more restrictive than the property's readonly - Allows the field to be initialized only once in a constructor. modifier. static - Makes the field a static member. Automatic properties This is a feature of C# 3.0. Properties Properties bring field-like syntax and combine them with the power of methods. A property can have two accessors: get and set. class Person A feature of C# 3.0 is auto-implemented properties. You define accessors without bodies and the compiler will generate a backing field and the necessary code for the accessors. public double Width { string name; { get; private set; string Name } { get { return name; } set { name = value; } } } // Using a property Person person = new Person(); person.Name = "Robert"; Modifiers for properties: private - Makes the property private (default). protected - Makes the property protected. public - Makes the property public. static - Makes the property a static member. Modifiers for property accessors: private - Makes the accessor private. protected - Makes the accessor protected. public - Makes the accessor public. Overview of .NET Framework release history