Sie sind auf Seite 1von 20

C Sharp syntax

The correct title of this article is C# syntax. The keywords in certain situations.[1] If an identier is needed
substitution or omission of the # is because of technical which would be the same as a reserved keyword, it may
restrictions. be prexed by the @ character to distinguish it. This fa-
cilitates reuse of .NET code written in other languages.[2]
Using a keyword as an identier:
Main article: C Sharp (programming language)
string @out; // @out is an ordinary identier, distinct
This article describes the syntax of the C# programming from the 'out' keyword, // which retains its special
language. The features described are compatible with meaning
.NET Framework and Mono.

1.2 Literals
1 Basics
1.3 Variables
1.1 Identier
Variables are identiers associated with values. They are
An identier is the name of an element in the code. There declared by writing the variables type and name, and are
are certain standard naming conventions to follow when optionally initialized in the same statement.
selecting names for elements. Declare
An identier can: int myInt; // Declaring an uninitialized variable called
'myInt', of type 'int'
start with an underscore: _

start with a dollar sign: $ Assigning


int myInt; // Declaring an uninitialized variable myInt =
contain an underscore: _
35; // Assigning the variable a value
contain a numeral: 0123456789
Initialize
contain both upper case and lower case Unicode let-
ters. Case is sensitive (BOX is dierent from box). int myInt = 35; // Declaring and initializing the variable

An identier cannot: Multiple variables of the same type can be declared and
initialized in one statement.
start with a numeral int a, b; // Declaring multiple variables of the same type
int a = 2, b = 3; // Declaring and initializing multiple
start with a symbol, unless it is a keyword (check
variables of the same type
Keywords)

have more than 511 chars

contain @ sign in between or at the end 1.3.1 Local variable type inference

This is a feature of C# 3.0.


1.1.1 Keywords
C# 3.0 introduced type inference, allowing the type spec-
Keywords are predened reserved words with special syn- ier of a variable declaration to be replaced by the key-
tactic meaning. The language has two types of keyword word var, if its actual type can be statically determined
contextual and reserved. The reserved keywords such from the initializer. This reduces repetition, especially
as false or byte may only be used as keywords. The con- for types with multiple generic type-parameters, and ad-
textual keywords such as where or from are only treated as heres more closely to the DRY principle.

1
2 3 OPERATORS

var myChars = new char[] {'A', ''}; // or char[] 2.1 Main method
myChars = new char[] {'A', ''}; var myNums = new
List<int>(); // or List<int> myNums = new List<int>(); Whether it is a console or a graphical interface applica-
tion, the program must have an entry point of some sort.
The entry point of the C# application is the Main method.
See also
There can only be one, and it is a static method in a class.
Type inference The method usually returns void and is passed command-
line arguments as an array of strings.
static void Main(string[] args) { } // OR Main method
1.4 Constants can be dened without parameters. static void Main() { }

Constants are immutable values.


A Main method is also allowed to return an integer value
if specied.
1.4.1 const
static int Main(string[] args) { return 0; }
When declaring a local variable or a eld with the const
keyword as a prex the value must be given when it is
declared. After that it is locked and cannot change. They 2.2 Namespaces
can either be declared in the context as a eld or a local
variable. Constants are implicitly static. Namespaces are a part of a type name and they are used to
const double PI = 3.14; group and/or distinguish named entities from other ones.
System.IO.DirectoryInfo // DirectoryInfo is in the
This shows all the uses of the keyword. System.IO-namespace
class Foo { const double X = 3; Foo() { const int Y = 2; } }
A namespace is dened like this:
namespace FooNamespace { // Members }
1.4.2 readonly

The readonly keyword does a similar thing to elds. Like


elds marked as const they cannot change once initialized. 2.3 using statement
The dierence is that you can choose to initialize them
in a constructor. This only works on elds. Read-only The using statement loads a specic namespace from a
elds can either be members of an instance or static class referenced assembly. It is usually placed in the top (or
members. header) of a code le but it can be placed elsewhere if
wanted, e.g. inside classes.
using System; using System.Collections;
1.5 Code blocks
The operators { ... } are used to signify a code block and a The statement can also be used to dene another name for
new scope. Class members and the body of a method are an existing namespace or type. This is sometimes useful
examples of what can live inside these braces in various when names are too long and less readable.
contexts. using Net = System.Net; using DirInfo = Sys-
Inside of method bodies you can use the braces to create tem.IO.DirectoryInfo;
new scopes like so:
void doSomething() { int a; { int b; a = 1; } a = 2; b = 3;
// Will fail because the variable is declared in an inner
scope. } 3 Operators

3.1 Operator overloading

2 Program structure Some of the existing operators can be overloaded by writ-


ing an overload method.
A C# application consists of classes and their members. public static Foo operator+(Foo foo, Bar bar) { return
Classes and other types exist in namespaces but can also new Foo(foo.Value + bar.Value); }
be nested inside other classes.
3

These are the overloadable operators: The following


return ifNotNullValue ?? otherwiseValue;
Assignment operators (+=, *= etc.) are combinations
of a binary operator and the assignment operator (=)
Is shorthand for
and will be evaluated using the ordinary operators,
which can be overloaded. return ifNotNullValue != null ? ifNotNullValue :
otherwiseValue;
Cast operators (( )) cannot be overloaded, but you
can dene conversion operators.
Meaning that if the content of variable ifNotNullValue
Array indexing ([ ]) operator is not overloadable, but is not null, that content will be returned, otherwise the
you can dene new indexers. content of variable otherwiseValue is returned.

See also
4 Control structures
Operator overloading
C# inherits most of the control structures of C/C++ and
also adds new ones like the foreach statement.
3.2 Conversion operators
4.1 Conditional structures
The cast operator is not overloadable but you can write
a conversion operator method which lives in the target
These structures control the ow of the program through
class. Conversion methods can dene two varieties of
given conditions.
operators, implicit and explicit conversion operators. The
implicit operator will cast without specifying with the cast
operator (( )) and the explicit operator requires it to be 4.1.1 if statement
used.
Implicit conversion operator The if statement is entered when the given condition is
true. Single-line case statements do not require block
braces although it is mostly preferred by convention.
class Foo { public int Value; public static implicit
operator Foo(int value) { return new Foo(value); } } // Simple one-line statement:
Implicit conversion Foo foo = 2; if (i == 3) ... ;

Explicit conversion operator Multi-line with else-block (without any braces):


if (i == 2) ... else ...
class Foo { public int Value; public static explicit
operator Foo(int value) { return new Foo(value); } } //
Explicit conversion Foo foo = (Foo)2; Recommended coding conventions for an if-statement.
if (i == 3) { ... } else if (i == 2) { ... } else { ... }

3.2.1 as operator
4.1.2 switch statement
The as operator will attempt to do a silent cast to a given
type. If it succeeds it will return the object as the new The switch construct serves as a lter for dierent val-
type, if it fails it will return a null reference. ues. Each value leads to a case. It is not allowed to fall
through case sections and therefore the keyword break is
Stream stream = File.Open(@"C:\Temp\data.dat);
typically used to end a case. An unconditional return in
FileStream fstream = stream as FileStream; // Will
a case section can also be used to end a case. See also
return an object. String str = stream as String; // Will fail
how goto statement can be used to fall through from one
and return null.
case to the next. Many cases may lead to the same code
though. The default case handles all the other cases not
handled by the construct.
3.3 Null coalesce operator switch (ch) { case 'A': statement; ... break; case 'B':
statement; break; case 'C': // A switch section can have
This is a feature of C# 2.0. multiple case labels. case 'D': ... break; default: ... break;
4 4 CONTROL STRUCTURES

} 4.3.1 Labels and goto statement

Labels are given points in code that can be jumped to by


using the goto statement.
4.2 Iteration structures start: ....... goto start;

Iteration statements are statements that are repeatedly ex-


The goto statement can be used in switch statements to
ecuted when a given condition is evaluated as true.
jump from one case to another or to fall through from
one case to the next.
4.2.1 while loop switch(n) { case 1: Console.WriteLine(Case 1);
break; case 2: Console.WriteLine(Case 2); goto case
while (i == true) { ... } 1; case 3: Console.WriteLine(Case 3); case 4: //
Compilation will fail here as cases cannot fall through in
C#. Console.WriteLine(Case 4); goto default; // This
is the correct way to fall through to the next case. default:
Console.WriteLine(Default); }
4.2.2 do ... while loop

do { } while (i == true);
4.3.2 break statement

The break statement breaks out of the closest loop or


4.2.3 for loop switch statement. Execution continues in the statement
after the terminated statement, if any.
The for loop consists of three parts: declaration, condition int e = 10; for (int i = 0; i < e; i++) { while (true) { break;
and increment. Any of them can be left out as they are } // Will break to this point. }
optional.
for (int i = 0; i < 10; i++) { ... }
4.3.3 continue statement
Is equivalent to this code represented with a while state-
ment. The continue statement discontinues the current iteration
of the current control statement and begins the next iter-
int i = 0; while (i < 10) { //... i++; }
ation.
int ch; while ((ch = Console.Read()) != 1) { if (ch == '
') continue; // Skips the rest of the while-loop // Rest of
4.2.4 foreach loop the while-loop ... }

The foreach statement is derived from the for statement The while loop in the code above reads characters by call-
and makes use of a certain pattern described in C#'s lan- ing GetChar(), skipping the statements in the body of the
guage specication in order to obtain and use an enumer- loop if the characters are spaces.
ator of elements to iterate over.
Each item in the given collection will be returned and
reachable in the context of the code block. When the
4.4 Exception handling
block has been executed the next item will be returned
Runtime exception handling method in C# is inherited
until there are no items remaining.
from Java and C++.
foreach (int i in intList) { ... }
The base class library has a class called System.Exception
from which all other exception classes are derived. An
Exception-object contains all the information about a spe-
cic exception and also the inner exceptions that were
4.3 Jump statements caused. Programmers may dene their own exceptions
by deriving from the Exception class.
Jump statements are inherited from C/C++ and ultimately
assembly languages through it. They simply represent the An exception can be thrown this way:
jump-instructions of an assembly language that controls throw new NotImplementedException();
the ow of a program.
5.2 Reference types 5

4.4.1 try ... catch ... nally statements tactical dierences between a class and a struct are pre-
sented later in this article.
Exceptions are managed within try ... catch blocks. struct Foo { ... }
try { // Statements which may throw exceptions ... }
catch (Exception ex) { // Exception caught and handled The primitive data types are all structs.
here ... } nally { // Statements always executed after
the try/catch blocks ... }
Pre-dened types These are the primitive datatypes.
The statements within the try block are executed, and if Note: string (System.String) is not a struct and is not a
any of them throws an exception, execution of the block primitive type.
is discontinued and the exception is handled by the catch
block. There may be multiple catch blocks, in which
case the rst block with an exception variable whose type 5.1.2 Enumerations
matches the type of the thrown exception is executed.
Enumerated types (enums) are named values representing
If no catch block matches the type of the thrown excep-
integer values.
tion, the execution of the outer block (or method) con-
taining the try ... catch statement is discontinued, and the enum Season { Winter = 0, Spring = 1, Summer = 2,
exception is passed up and outside the containing block Autumn = 3, Fall = Autumn // Autumn is called Fall in
or method. The exception is propagated upwards through American English. }
the call stack until a matching catch block is found within
one of the currently active methods. If the exception enum variables are initialized by default to zero. They can
propagates all the way up to the top-most Main() method be assigned or initialized to the named values dened by
without a matching catch block being found, the entire the enumeration type.
program is terminated and a textual description of the
exception is written to the standard output stream. Season season; season = Season.Spring;
The statements within the nally block are always exe-
cuted after the try and catch blocks, whether or not an enum type variables are integer values. Addition and sub-
exception was thrown. Such blocks are useful for provid- traction between variables of the same type is allowed
ing clean-up code. without any specic cast but multiplication and division is
somewhat more risky and requires an explicit cast. Casts
Either a catch block, a nally block, or both, must follow are also required for converting enum variables to and
the try block. from integer types. However, the cast will not throw an
exception if the value is not specied by the enum type
denition.
5 Types season = (Season)2; // cast 2 to an enum-value of type
Season. season = season + 1; // Adds 1 to the value. sea-
C# is a statically typed language like C and C++. That son = season + season2; // Adding the values of two enum
means that every variable and constant gets a xed type variables. int value = (int)season; // Casting enum-value
when it is being declared. There are two kinds of types: to integer value. season++; // Season.Spring (1) becomes
value types and reference types. Season.Summer (2). season--; // Season.Summer (2)
becomes Season.Spring (1).

5.1 Value types Values can be combined using the bitwise-OR operator .
Color myColors = Color.Green | Color.Yellow |
Instances of value types reside on the stack, i.e. they are Color.Blue;
bound to their variables. If you declare a variable for a
value type the memory gets allocated directly. If the vari-
able gets out of scope the object is destroyed with it. See also

Enumeration (programming)
5.1.1 Structures

Structures are more commonly known as structs. Structs 5.2 Reference types
are user-dened value types that are declared using the
struct keyword. They are very similar to classes but are Variables created for reference types are typed managed
more suitable for lightweight types. Some important syn- references. When the constructor is called, an object is
6 5 TYPES

created on the heap and a reference is assigned to the vari- Actions performed on a string will always return a new
able. When a variable of an object gets out of scope the string.
reference is broken and when there are no references left string text = Hello World!"; string substr =
the object gets marked as garbage. The garbage collector text.Substring(0, 5); string[] parts = text.Split(new
will then soon collect and destroy it. char[]{ ' ' });
A reference variable is null when it does not reference any
object.
The System.StringBuilder class can be used when a mu-
table string is wanted.
5.2.1 Arrays StringBuilder sb = new StringBuilder(); sb.Append('H');
sb.Append(el); sb.AppendLine(lo!");
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, Sys-
tem.Array. Each element is referenced by its index just 5.2.3 Interface
like in C++ and Java.
Interfaces are data structures that contain member de-
An array in C# is what would be called a dynamic array
nitions with no actual implementation. A variable of an
in C++.
interface type is a reference to an instance of a class which
int[] numbers = new int[2]; numbers[0] = 2; numbers[1] implements this interface. See #Interfaces.
= 5; int x = numbers[0];

5.2.4 Delegates

Initializers Array initializers provide convenient syn- Main article: Delegate (CLI)
tax for initialization of arrays.
// Long syntax int[] numbers = new int[5]{ 20, 1, 42, 15, C# provides type-safe object-oriented function pointers
34 }; // Short syntax int[] numbers2 = { 20, 1, 42, 15, 34 in the form of delegates.
}; // Inferred syntax var numbers3 = new[] { 20, 1, 42,
class Program { // Delegate type . delegate int Opera-
15, 34 };
tion(int a, int b); static int Add(int i1, int i2) { return i1 +
i2; } static int Sub(int i1, int i2) { return i1 - i2; } static
void Main() { // Instantiate the delegate and assign the
Multi-dimensional arrays Arrays can have more than method to it. Operation op = Add; // Call the method
one dimension, for example 2 dimensions to represent a that the delegate points to. int result1 = op(2, 3); // 5 op
grid. = Sub; int result2 = op(10, 2); // 8 } }
int[,] numbers = new int[3, 3]; numbers[1,2] = 2; int[,]
numbers2 = new int[3, 3] { {2, 3, 2}, {1, 2, 6}, {2, 4, 5} Initializing the delegate with an anonymous method.
}; addition = delegate(int a, int b){ return a + b; };

See also Initializing the delegate with lambda expression.


addition = (a, b) => a + b;
Jagged array

5.2.2 Classes 5.2.5 Events

Classes are self-describing user-dened reference types. Events are pointers that can point to multiple methods.
Essentially all types in the .NET Framework are classes, More exactly they bind method pointers to one identier.
including structs and enums, that are compiler generated This can therefore be seen as an extension to delegates.
classes. Class members are private by default, but can They are typically used as triggers in UI development.
be declared as public to be visible outside of the class or The form used in C# and the rest of the Common Lan-
protected to be visible by any descendants of the class. guage Infrastructure is based on that in the classic Visual
Basic.
String class The System.String class, or simply string, delegate void MouseEventHandler(object sender,
represents an immutable sequence of unicode characters MouseEventArgs e); public class Button : Sys-
(char). tem.Windows.Controls.Control { event MouseEven-
5.2 Reference types 7

tHandler OnClick; /* Imaginary trigger function */ void 5.2.7 Pointers


click() { this.OnClick(this, new MouseEventArgs(data));
}} C# has and allows pointers to selected types (some primi-
tives, enums, strings, pointers, and even arrays and structs
if they contain only types that can be pointed[4] ) in unsafe
An event requires an accompanied event handler that
context: methods and codeblock marked unsafe. These
is made from a special delegate that in a platform spe-
are syntactically the same as pointers in C and C++. How-
cic library like in Windows Presentation Foundation and
ever, runtime-checking is disabled inside unsafe blocks.
Windows Forms usually takes two parameters: sender
and the event arguments. The type of the event argument- static void Main(string[] args) { unsafe { int a = 2; int*
object derive from the EventArgs class that is a part of the b = &a; Console.WriteLine(Address of a: {0}. Value:
CLI base library. {1}", (int)&a, a); Console.WriteLine(Address of b:
{0}. Value: {1}. Value of *b: {2}", (int)&b, (int)b,
Once declared in its class the only way of invoking the
*b); // Will output something like: // Address of a:
event is from inside of the owner. A listener method may
71953600. Value: 2 // Address of b: 71953596. Value:
be implemented outside to be triggered when the event is
71953600. Value of *b: 2 } }
red.
public class MainWindow : Sys-
Structs are required only to be pure structs with no mem-
tem.Windows.Controls.Window { private Button but-
bers of a managed reference type, e.g. a string or any
ton1; public MainWindow() { button1 = new Button();
other class.
button1.Text = Click me!"; /* Subscribe to the event */
button1.ClickEvent += button1_OnClick; /* Alternate public struct MyStruct { public char Character; public
syntax that is considered old: button1.MouseClick int Integer; } public struct MyContainerStruct { public
+= new MouseEventHandler(button1_OnClick); */ byte Byte; public MyStruct MyStruct; }
} protected void button1_OnClick(object sender,
MouseEventArgs e) { MessageBox.Show(Clicked!"); } In use:
}
MyContainerStruct x; MyContainerStruct* ptr = &x;
byte value = ptr->Byte;
Custom event implementation is also possible:
private EventHandler clickHandles = (s, e) => { }; public See also
event EventHandler Click { add { // Some code to run
when handler is added... ... clickHandles += value; } Pointer (programming)
remove { // Some code to run when handler is removed...
... clickHandles -= value; } }
5.2.8 Dynamic
See also This is a feature of C# 4.0 and .NET Frame-
work 4.0.

Event-driven programming Type dynamic is a feature that enables dynamic runtime


lookup to C# in a static manner. Dynamic denotes a vari-
able with an object with a type that is resolved at runtime,
as opposed to compile-time, as normally is done.
5.2.6 Nullable types
This feature takes advantage of the Dynamic Lan-
guage Runtime (DLR) and has been designed speci-
This is a feature of C# 2.0. cally with the goal of interoping with dynamically typed
languages like IronPython and IronRuby (Implementa-
tions of Python and Ruby for .NET).
Nullable types were introduced in C# 2.0 rstly to en- Dynamic-support also eases interop with COM objects.
able value types to be null (useful when working with a
database). dynamic x = new Foo(); x.DoSomething(); // Will
compile and resolved at runtime. An exception will be
int? n = 2; n = null; Console.WriteLine(n.HasValue); thrown if invalid.

In reality this is the same as using the Nullable<T> struct.


Nullable<int> n = 2; n = null; Con- 5.2.9 Anonymous types
sole.WriteLine(n.HasValue);
This is a feature of C# 3.0.
8 6 OBJECT-ORIENTED PROGRAMMING (OOP)

Anonymous types are nameless classes that are generated Members


by the compiler. They are only consumable and yet very Some of the members of the Object class:
useful in a scenario like where you have a LINQ query
which returns an object on select and you just want to re- Equals - Supports comparisons between objects.
turn some specic values. Then you can dene an anony-
mous type containing auto-generated read-only elds for
the values. Finalize - Performs cleanup operations before an ob-
ject is automatically reclaimed. (Default destructor)
When instantiating another anonymous type declaration
with the same signature the type is automatically inferred
by the compiler. GetHashCode - Gets the number corresponding to
the value of the object to support the use of a hash
var carl = new { Name = Carl, Age = 35 }; // Name table.
of the type is only known by the compiler. var mary =
new { Name = Mary, Age = 22 }; // Same type as the
expression above GetType - Gets the Type of the current instance.

ToString - Creates a human-readable text string that


describes an instance of the class. Usually it returns
5.3 Boxing and unboxing the name of the type.

Boxing is the operation of converting a value of a value


type into a value of a corresponding reference type.[5] 6.2 Classes
Boxing in C# is implicit.
Unboxing is the operation of converting a value of a ref- Classes are fundamentals of an object-oriented language
erence type (previously boxed) into a value of a value such as C#. They serve as a template for objects. They
type.[5] Unboxing in C# requires an explicit type cast. contain members that store and manipulate data in a real-
lifelike way.
Example:
See also
int foo = 42; // Value type. object bar = foo; // foo is
boxed to bar. int foo2 = (int)bar; // Unboxed back to
value type. Class (computer science)

Structure (computer science)

6 Object-oriented programming 6.2.1 Dierences between classes and structs


(OOP)
Although classes and structures are similar in both the
C# has direct support for object-oriented programming. way they are declared and how they are used, there are
some signicant dierences. Classes are reference types
and structs are value types. A structure is allocated on
6.1 Objects the stack when it is declared and the variable is bound
to its address. It directly contains the value. Classes are
An object is created with the type as a template and is dierent because the memory is allocated as objects on
called an instance of that particular type. the heap. Variables are rather managed pointers on the
stack which point to the objects. They are references.
In C#, objects are either references or values. No further
syntactical distinction is made between those in code. Structures require some more work than classes. For
example, you need to explicitly create a default con-
structor which takes no arguments to initialize the struct
6.1.1 object class and its members. The compiler will create a default
one for classes. All elds and properties of a struct
All types, even value types in their boxed form, implic- must have been initialized before an instance is cre-
itly inherit from the System.Object class which is the ul- ated. Structs do not have nalizers and cannot inherit
timate base class of all objects. The class contains the from another class like classes do. However, they in-
most common methods shared by all objects. Some of herit from System.ValueType, that inherits from Sys-
these are virtual and can be overridden. tem.Object. Structs are more suitable for smaller con-
Classes inherit System.Object either directly or indirectly structs of data.
through another base class. This is a short summary of the dierences:
6.2 Classes 9

6.2.2 Declaration 6.2.4 Accessing members

A class is declared like this: Members of an instance and static members of a class are
class Foo { // Member declarations } accessed using the . operator.
Accessing an instance member
Instance members can be accessed through the name of
a variable.
Partial class
string foo = Hello"; string fooUpper = foo.ToUpper();
This is a feature of C# 2.0.
Accessing a static class member
A partial class is a class declaration whose code is divided Static members are accessed by using the name of the
into separate les. The dierent parts of a partial class class or other type.
must be marked with keyword partial.
int r = String.Compare(foo, fooUpper);
// File1.cs partial class Foo { ... } // File2.cs partial class
Foo { ... }
Accessing a member through a pointer
In unsafe code, members of a value (struct type) refer-
enced by a pointer are accessed with the -> operator just
6.2.3 Initialization like in C and C++.

Before you can use the members of the class you need POINT p; p.X = 2; p.Y = 6; POINT* ptr = &p; ptr->Y
to initialize the variable with a reference to an object. To = 4;
create it you call the appropriate constructor using the new
keyword. It has the same name as the class.
Foo foo = new Foo(); 6.2.5 Modiers

Modiers are keywords used to modify declarations of


For structs it is optional to explicitly call a constructor be-
types and type members. Most notably there is a sub-
cause the default one is called automatically. You just
group containing the access modiers.
need to declare it and it gets initialized with standard val-
ues.
Class modiers
Object initializers
abstract - Species that a class only serves as a base
This is a feature of C# 3.0. class. It must be implemented in an inheriting class.

Provides a more convenient way of initializing public sealed - Species that a class cannot be inherited.
elds and properties of an object. Constructor calls are
optional when there is a default constructor. Class member modiers
Person person = new Person { Name = John Doe,
Age = 39 }; // Equal to Person person = new Person(); const - Species that a variable is a constant value
person.Name = John Doe"; person.Age = 39; that has to be initialized when it gets declared.

event - Declares an event.

Collection initializers extern - Specify that a method signature without a


body uses a DLL-import.
This is a feature of C# 3.0.
override - Specify that a method or property decla-
Collection initializers give an array-like syntax for initial- ration is an override of a virtual member or an im-
izing collections. The compiler will simply generate calls plementation of a member of an abstract class.
to the Add-method. This works for classes that imple-
ment the interface ICollection. readonly - Declare a eld that can only be assigned
values as part of the declaration or in a constructor
List<int> list = new List<int> {2, 5, 6, 6}; // Equal to in the same class.
List<int> list = new List<int>(); list.Add(2); list.Add(5);
list.Add(6); list.Add(6); unsafe - Species an unsafe context, which allows
the use of pointers.
10 6 OBJECT-ORIENTED PROGRAMMING (OOP)

virtual - Species that a method or property decla- The syntax is similar to the one of constructors. The dif-
ration can be overridden by a derived class. ference is that the name is preceded by a ~ and it cannot
contain any parameters. There cannot be more than one
volatile - Species a eld which may be modied
destructor..
by an external process and prevents an optimizing
compiler from modifying the use of the eld. class Foo { ... ~Foo() { ... } }

static modier The static modier states that a mem- Finalizers are always private.
ber belongs to the class and not to a specic object. See also
Classes marked static are only allowed to contain static
members. Static members are sometimes referred to as Destructor (computer science)
class members since they apply to the class as a whole and
not to its instances.
6.2.8 Methods
public class Foo { public static void Something() { ... }
} // Calling the class method. Foo.Something(); Like in C and C++ there are functions that group reusable
code. The main dierence is that functions, just like in
Java, have to reside inside of a class. A function is there-
Access modiers The access modiers, or inheritance fore called a method. A method has a return value, a name
modiers, set the accessibility of classes, methods, and and usually some parameters initialized when it is called
other members. Something marked public can be with some arguments. It can either belong to an instance
reached from anywhere. private members can only be of a class or be a static member.
accessed from inside of the class they are declared in and class Foo { int Bar(int a, int b) { return a%b; } }
will be hidden when inherited. Members with the pro-
tected modier will be private, but accessible when inher-
ited. internal classes and members will only be accessible A method is called using . notation on a specic variable,
from the inside of the declaring assembly. or as in the case of static methods, the name of a type.

Classes and structs are implicitly internal and members Foo foo = new Foo(); int r = foo.Bar(7, 2); Con-
are implicitly private if they do not have an access modi- sole.WriteLine(r);
er.
public class Foo { public int Do() { return 0; } public See also
class Bar { } }
Method (computer science)

This table denes where the access modiers can be used.


ref and out parameters One can explicitly make ar-
guments be passed by reference when calling a method
6.2.6 Constructors with parameters preceded by keywords ref or out. These
managed pointers come in handy when passing variables
A constructor is a special method that is called automati- that you want to be modied inside the method by refer-
cally when an object is created. Its purpose is to initialize ence. The main dierence between the two is that an out
the members of the object. Constructors have the same parameter must have been assigned within the method by
name as the class and do not return anything. They may the time the method returns, while ref need not assign a
take parameters like any other method. value.
class Foo { Foo() { ... } } void PassRef(ref int x) { if(x == 2) x = 10; } int Z;
PassRef(ref Z); void PassOut(out int x) { x = 2; } int Q;
Constructors can be public, private, or internal. PassOut(out Q);
See also

Constructor (computer science) Optional parameters

6.2.7 Destructor This is a feature of C# 4.0.

The destructor is called when the object is being collected C# 4.0 introduces optional parameters with default values
by the garbage collector to perform some manual clean- as seen in C++. For example:
up. There is a default destructor method called nalize void Increment(ref int x, int dx = 1) { x += dx; } int x
that can be overridden by declaring your own. = 0; Increment(ref x); // dx takes the default value of 1
6.2 Classes 11

Increment(ref x, 2); // dx takes the value 2 Fields can be initialized directly when declared (unless
declared in struct).
In addition, to complement optional parameters, it is pos- class Foo { double foo = 2.3; }
sible to explicitly specify parameter names in method
calls, allowing to selectively pass any given subset of op-
Modiers for elds:
tional parameters for a method. The only restriction is
that named parameters must be placed after the unnamed const - Makes the eld a constant.
parameters. Parameter names can be specied for both
optional and required parameters, and can be used to private - Makes the eld private (default).
improve readability or arbitrarily reorder arguments in a
protected - Makes the eld protected.
call. For example:
Stream OpenFile(string name, FileMode mode = File- public - Makes the eld public.
Mode.Open, FileAccess access = FileAccess.Read) readonly - Allows the eld to be initialized only once
{ ... } OpenFile(le.txt); // use default values for in a constructor.
both mode and access OpenFile(le.txt, mode:
FileMode.Create); // use default value for access static - Makes the eld a static member.
OpenFile(le.txt, access: FileAccess.Read); // use
default value for mode OpenFile(name: le.txt, 6.2.10 Properties
access: FileAccess.Read, mode: FileMode.Create); //
name all parameters for extra readability, // and use Properties bring eld-like syntax and combine them with
order dierent from method declaration the power of methods. A property can have two acces-
sors: get and set.
Optional parameters make interoperating with COM eas- class Person { string name; string Name { get { return
ier. Previously, C# had to pass in every parameter in the name; } set { name = value; } } } // Using a property
method of the COM component, even those that are op- Person person = new Person(); person.Name = Robert";
tional. For example:
object leName = Test.docx"; object missing = Sys- Modiers for properties:
tem.Reection.Missing.Value; doc.SaveAs(ref leName,
ref missing, ref missing, ref missing, ref missing, ref private - Makes the property private (default).
missing, ref missing, ref missing, ref missing, ref miss-
ing, ref missing, ref missing, ref missing, ref missing, protected - Makes the property protected.
ref missing, ref missing); console.writeline(File saved
public - Makes the property public.
successfully);
static - Makes the property a static member.
With support for optional parameters, the code can be
shortened as Modiers for property accessors:

doc.SaveAs(ref leName); private - Makes the accessor private.


protected - Makes the accessor protected.
public - Makes the accessor public.
extern A feature of C# is the ability to call native code.
A method signature is simply declared without a body and The default modiers for the accessors are inherited from
is marked as extern. The DllImport attribute also needs the property. Note that the accessors modiers can only
to be added to reference the desired DLL le. be equal or more restrictive than the propertys modier.
[DllImport(win32.dll)] static extern double
Pow(double a, double b); Automatic properties

This is a feature of C# 3.0.

6.2.9 Fields A feature of C# 3.0 is auto-implemented properties. You


dene accessors without bodies and the compiler will
Fields, or class variables, can be declared inside the class generate a backing eld and the necessary code for the
body to store data. accessors.
class Foo { double foo; } public double Width { get; private set; }
12 6 OBJECT-ORIENTED PROGRAMMING (OOP)

6.2.11 Indexers abstract class Mammal { public abstract void Walk(); }


class Human : Mammal { public override void Walk() {
Indexers add array-like indexing capabilities to objects. } ... }
They are implemented in a way similar to properties.
class IntList { int[] items; int this[int index] { get { return
this.items[index]; } set { this.items[index] = value; } } }
sealed The sealed modier can be combined with the
// Using an indexer IntList list = new IntList(); list[2] =
others as an optional modier for classes to make them
2;
uninheritable.
internal sealed class _FOO { }

6.2.12 Inheritance

Classes in C# may only inherit from one class. A class 6.3 Interfaces
may derive from any class that is not marked as sealed.
class A { } class B : A { } Interfaces are data structures that contain member de-
nitions and not actual implementation. They are useful
when you want to dene a contract between members in
See also
dierent types that have dierent implementations. You
can declare denitions for methods, properties, and in-
Inheritance (computer science) dexers. Interface members are implicitly public. An in-
terface can either be implicitly or explicitly implemented.
virtual Methods marked virtual provide an implemen- interface IBinaryOperation { double A { get; set; }
tation, but they can be overridden by the inheritors by double B { get; set; } double GetResult(); }
using the override keyword.
The implementation is chosen by the actual type of the
object and not the type of the variable.
6.3.1 Implementing an interface
class Operation { public virtual int Do() { return 0; }
} class NewOperation : Operation { public override int An interface is implemented by a class or extended by
Do() { return 1; } } another interface in the same way you derive a class from
another class using the : notation.
Implicit implementation
new When overloading a non-virtual method with an- When implicitly implementing an interface the members
other signature, the keyword new may be used. The used of the interface have to be public.
method will be chosen by the type of the variable instead
of the actual type of the object. public class Adder : IBinaryOperation { public double A
{ get; set; } public double B { get; set; } public double
class Operation { public int Do() { return 0; } } class GetResult() { return A + B; } } public class Multiplier :
NewOperation : Operation { public new double Do() { IBinaryOperation { public double A { get; set; } public
return 4.0; } } double B { get; set; } public double GetResult() { return
A*B; } }
This demonstrates the case:
NewOperation operation = new NewOperation(); // In use:
Will call double Do()" in NewOperation double d = IBinaryOperation op = null; double result; // Adder
operation.Do(); Operation operation_ = operation; // implements the interface IBinaryOperation. op = new
Will call int Do()" in Operation int i = operation_.Do(); Adder(); op.A = 2; op.B = 3; result = op.GetResult(); //
5 // Multiplier also implements the interface. op = new
Multiplier(); op.A = 5; op.B = 4; result = op.GetResult();
abstract Abstract classes are classes that only serve as // 20
templates and you can not initialize an object of that type.
Otherwise it is just like an ordinary class. Explicit implementation
There may be abstract members too. Abstract members You can also explicitly implement members. The mem-
are members of abstract classes that do not have any im- bers of the interface that are explicitly implemented by
plementation. They must be overridden by the class that a class are accessible only when the object is handled as
inherits the member. the interface type.
13

public class Adder : IBinaryOperation { double IBina- 7 Generics


ryOperation.A { get; set; } double IBinaryOperation.B
{ get; set; } double IBinaryOperation.GetResult() {
return ((IBinaryOperation)this).A + ((IBinaryOpera- This is a feature of C# 2.0 and .NET Frame-
tion)this).B; } } work 2.0.

In use:
Adder add = new Adder(); // These members are not See also: Generic programming
accessible: // add.A = 2; // add.B = 3; // double result =
add.GetResult(); // Cast to the interface type to access Generics (or parameterized types, parametric polymor-
them: IBinaryOperation add2 = add; add2.A = 2; add2.B phism) use type parameters, which make it possible to
= 3; double result = add2.GetResult(); design classes and methods that do not specify the type
used until the class or method is instantiated. The main
Note: The properties in the class that extends IBinaryOp- advantage is that one can use generic type parameters to
eration are auto-implemented by the compiler and a back- create classes and methods that can be used without in-
ing eld is automatically added (see #Automatic proper- curring the cost
[6]
of runtime casts or boxing operations, as
ties). shown here:

Extending multiple interfaces // Declare the generic class. public class GenericList<T>
{ void Add(T input) { } } class TestGenericList {
Interfaces and classes are allowed to extend multiple in- private class ExampleClass { } static void Main()
terfaces. { // Declare a list of type int. GenericList<int>
class MyClass : IInterfaceA, IInterfaceB { ... } list1 = new GenericList<int>(); // Declare a list of
type string. GenericList<string> list2 = new Generi-
cList<string>(); // Declare a list of type ExampleClass.
Here is an interface that extends two interfaces.
GenericList<ExampleClass> list3 = new Generi-
interface IInterfaceC : IInterfaceA, IInterfaceB { ... } cList<ExampleClass>(); } }

When compared with C++ templates, C# generics can


provide enhanced safety, but also have somewhat limited
6.3.2 Interfaces vs. abstract classes capabilities.[7] For example, it is not possible to call arith-
metic operators on a C# generic type.[8] Unlike C++ tem-
Interfaces and abstract classes are similar. The following plates, .NET parameterized types are instantiated at run-
describes some important dierences: time rather than by the compiler; hence they can be cross-
language whereas C++ templates cannot. They support
some features not supported directly by C++ templates
An abstract class may have member variables as well
such as type constraints on generic parameters by use of
as non-abstract methods or properties. An interface
interfaces. On the other hand, C# does not support non-
cannot.
type generic parameters.

A class or abstract class can only inherit from one Unlike generics in Java, .NET generics use reication
class or abstract class. to make parameterized types rst-class objects in the
Common Language Infrastructure (CLI) Virtual Ma-
chine, which allows for optimizations and preservation of
A class or abstract class may implement one or more
the type information.[9]
interfaces.

An interface can only extend other interfaces.


7.1 Using generics
An abstract class may have non-public methods and
properties (also abstract ones). An interface can
only have public members. 7.1.1 Generic classes

An abstract class may have constants, static methods Classes and structs can be generic.
and static members. An interface cannot. public class List<T> { ... public void Add(T item) {
... } } List<int> list = new List<int>(); list.Add(6);
An abstract class may have constructors. An inter- list.Add(2);
face cannot.
14 8 ENUMERATORS

7.1.2 Generic interfaces Therefore, any class that implements IEnumer-


able<Derived> for some class Derived is also considered
interface IEnumerable<T> { ... } to be compatible with IEnumerable<Base> for all classes
and interfaces Base that Derived extends, directly, or
indirectly. In practice, it makes it possible to write code
such as:
7.1.3 Generic delegates
void PrintAll(IEnumerable<object> objects) { foreach
delegate R Func<T1, T2, R>(T1 a1, T2 a2); (object o in objects) { System.Console.WriteLine(o);
} } IEnumerable<string> strings = new List<string>();
PrintAll(strings); // IEnumerable<string> is implicitly
converted to IEnumerable<object>
7.1.4 Generic methods
For contravariance, the existing interface IComparer<T>
public static T[] CombineArrays<T>(T[] a, T[] b) has been redened as follows:
{ T[] newArray = new T[a.Length + b.Length];
a.CopyTo(newArray, 0); b.CopyTo(newArray, public interface IComparer<in T> { int Compare(T x, T
a.Length); return newArray; } string[] a = new y); }
string[] { a, b, c }; string[] b = new string[] { 1,
2, 3 }; string[] c = CombineArrays(a, b); double[] Therefore, any class that implements IComparer<Base>
da = new double[] { 1.2, 2.17, 3.141592 }; double[] for some class Base is also considered to be compatible
db = new double[] { 4.44, 5.6, 6.02 }; double[] dc = with IComparer<Derived> for all classes and interfaces
CombineArrays(da, db); // c is a string array containing Derived that are extended from Base. It makes it possible
{ a, b, c, 1, 2, 3"} // dc is a double array to write code such as:
containing { 1.2, 2.17, 3.141592, 4.44, 5.6, 6.02}
IComparer<object> objectComparer = GetComparer();
IComparer<string> stringComparer = objectComparer;

7.2 Type-parameters

Type-parameters are names used in place of concrete 8 Enumerators


types when dening a new generic. They may be associ-
ated with classes or methods by placing the type parame-
An enumerator is an iterator. Enumerators are typically
ter in angle brackets < >. When instantiating (or calling)
obtained by calling the GetEnumerator() method of an
a generic, you can then substitute a concrete type for the
object implementing the IEnumerable interface. Con-
type-parameter you gave in its declaration. Type parame-
tainer classes typically implement this interface. How-
ters may be constrained by use of the where keyword and
ever, the foreach statement in C# can operate on any ob-
a constraint specication, any of the six comma separated
ject providing such a method, even if it doesn't implement
constraints may be used:[10]
IEnumerable. This interface was expanded into generic
version in .NET 2.0.
7.2.1 Covariance and contravariance The following shows a simple use of iterators in C# 2.0:
// explicit version IEnumerator<MyType> iter =
This is a feature of C# 4.0 and .NET Frame-
list.GetEnumerator(); while (iter.MoveNext()) Con-
work 4.0.
sole.WriteLine(iter.Current); // implicit version foreach
(MyType value in list) Console.WriteLine(value);
See also: Covariance and contravariance

Generic interfaces and delegates can have their type pa-


rameters marked as covariant or contravariant, using key- 8.1 Generator functionality
words out and in, respectively. These declarations are
then respected for type conversions, both implicit and This is a feature of C# 2.0.
explicit, and both compile-time and run-time. For ex-
ample, the existing interface IEnumerable<T> has been The .NET 2.0 Framework allowed C# to introduce an
redened as follows: iterator that provides generator functionality, using a
interface IEnumerable<out T> { IEnumerator<T> yield return construct similar to yield in Python.[11] With
GetEnumerator(); } a yield return, the function automatically keeps its state
during the iteration.
10.1 Anonymous delegates 15

// Method that takes an iterable input (possibly an array) Anonymous function


// and returns all even numbers. public static IEnu-
merable<int> GetEven(IEnumerable<int> numbers) { Closure (computer science)
foreach (int i in numbers) { if (i%2 == 0) yield return
i; } } //using the method to output only even numbers
from the array static void Main() { int[] numbers = { 10.1 Anonymous delegates
1, 2, 3, 4, 5, 6}; foreach (int i in GetEven(numbers))
Console.WriteLine(i); //outputs 2, 4 and 6 } This is a feature of C# 2.0.

Anonymous delegates are functions pointers that hold


anonymous methods. The purpose is to make it simpler to
9 LINQ use delegates by simplifying the process of assigning the
function. Instead of declaring a separate method in code
This is a feature of C# 3.0 and .NET Frame- the programmer can use the syntax to write the code in-
work 3.0. line and the compiler will then generate an anonymous
function for it.
Main article: LINQ Func<int, int> f = delegate(int x) { return x*2; };

LINQ, short for Language Integrated Queries, is a .NET


Framework feature which simplies the handling of data.
Mainly it adds support that allows you to query arrays, 10.2 Lambda expressions
collections, and databases. It also introduces binders,
which makes it easier to access to databases and their This is a feature of C# 3.0.
data.
Lambda expressions provide a simple syntax for inline
functions that are similar to closures. Functions with pa-
9.1 Query syntax rameters infer the type of the parameters if other is not
explicitly specied.
The LINQ query syntax was introduced in C# 3.0 and lets
you write SQL-like queries in C#. // [arguments] => [method-body] // With parameters n
=> n == 2 (a, b) => a + b (a, b) => { a++; return a + b; }
var list = new List<int>{ 2, 7, 1, 3, 9 }; var result = from // With explicitly typed parameters (int a, int b) => a + b
i in list where i > 1 select i; // No parameters () => return 0 // Assigning lambda to
delegate Func<int, int, int> f = (a, b) => a + b;
The statements are compiled into method calls, whereby
almost only the names of the methods are specied. Multi-statement lambdas have bodies enclosed by braces
Which methods are ultimately used is determined by nor- and inside of them code can be written like in standard
mal overload resolution. Thus, the end result of the trans- methods.
lation is aected by what symbols are in scope.
(a, b) => { a++; return a + b; }
What diers from SQL is that the from-statement comes
rst and not last as in SQL. This is because it seems more
natural writing like this in C# and supports Intellisense Lambda expressions can be passed as arguments directly
(Code completion in the editor). in method calls similar to anonymous delegates but with
a more aesthetic syntax.
var list = stringList.Where(n => n.Length > 2);
10 Anonymous methods
Lambda expressions are essentially compiler-generated
Anonymous methods, or in their present form more com- methods that are passed via delegates. These methods
monly referred to as lambda expressions, is a feature are reserved for the compiler only and can not be used in
which allows you to write inline closure-like functions in any other context.
your code.
There are various ways to create anonymous methods.
Prior to C# 3.0 there was limited support by using del- 11 Extension methods
egates.
See also This is a feature of C# 3.0.
16 12 MISCELLANEOUS

Extension methods are a form of syntactic sugar pro- [CompilerGenerated] public class $Anony-
viding the illusion of adding new methods to the exist- mousType$120 { [CompilerGenerated] public string
ing class outside its denition. In practice, an extension Name { get; set; } }
method is a static method that is callable as if it were an
instance method; the receiver of the call is bound to the The .NET Framework comes with predened attributes
rst parameter of the method, decorated with keyword that can be used. Some of them serve an important role
this: at runtime while some are just for syntactic decoration
public static class StringExtensions { public static string in code like CompilerGenerated. It does only mark that
Left(this string s, int n) { return s.Substring(0, n); } it is a compiler-generated element. Programmer-dened
} string s = foo"; s.Left(3); // same as StringExten- attributes can also be created.
sions.Left(s, 3); An attribute is essentially a class which inherits from the
System.Attribute class. By convention, attribute classes
See also end with Attribute in their name. This will not be re-
quired when using it.
Decorator pattern public class EdibleAttribute : Attribute { public Edi-
bleAttribute() : base() { } public EdibleAttribute(bool
isNotPoisonous) { this.IsPoisonous = !isNotPoisonous; }
public bool IsPoisonous { get; set; } }
12 Miscellaneous
Showing the attribute in use using the optional construc-
12.1 Closure blocks tor parameters.

C# implements closure blocks by means of the using [Edible(true)] public class Peach : Fruit { // Members if
statement. The using statement accepts an expression any }
which results in an object implementing IDisposable, and
the compiler generates code that guarantees the objects
disposal when the scope of the using-statement is exited.
The using statement is syntactic sugar. It makes the code 12.4 Preprocessor
more readable than the equivalent try ... nally block.
C# features preprocessor directives[12] (though it does
public void Foo() { using (var bar = File.Open(Foo.txt))
not have an actual preprocessor) based on the C prepro-
{ // do some work throw new Exception(); // bar will still
cessor that allow programmers to dene symbols, but not
get properly disposed. } }
macros. Conditionals such as #if, #endif, and #else are
also provided.
Directives such as #region give hints to editors for code
12.2 Thread synchronization folding. The #region block must be terminated with a
#endregion directive.
C# provides the lock statement, which is yet another ex- public class Foo { #region Constructors public Foo() {}
ample of benecial syntactic sugar. It works by marking public Foo(int rstParam) {} #endregion #region Proce-
a block of code as a critical section by mutual exclusion dures public void IntBar(int rstParam) {} public void
of access to a provided object. Like the using statement, StrBar(string rstParam) {} public void BoolBar(bool
it works by the compiler generating a try ... nally block rstParam) {} #endregion }
in its place.
private static StreamWriter _writer; public void Concur-
rentMethod() { lock (_writer) { _writer.WriteLine(Line
1.); _writer.WriteLine(Followed by line 2.); } } 12.5 Code comments

C# utilizes a double slash (//) to indicate the rest of the


line is a comment.
12.3 Attributes public class Foo { // a comment public static void Bar(int
rstParam) {} // Also a comment }
Attributes are entities of data that are stored as metadata
in the compiled assembly. An attribute can be added
to types and members like properties and methods. At- Multi-line comments can be indicated by a starting
tributes can be used for better maintenance of preproces- slash/asterisk (/*) and ending asterisk/forward slash (*/).
sor directives. public class Foo { /* A Multi-Line comment */ public
17

static void Bar(int rstParam) {} } markup is dened in a non-normative annex of the


ECMA C# standard. The same standard also denes rules
Comments do not nest. These are two single comments. for processing of such comments, and their transforma-
tion to a plain XML document with precise rules for map-
// Can put /* */ */ */ /* /* ping of Common Language Infrastructure (CLI) identi-
/* Can put /* /* /* but it ends with */ ers to their related documentation elements. This al-
lows any C# integrated development environment (IDE)
Single-line comments beginning with three slashes are or other development tool to nd documentation for any
used for XML documentation. This, however, is a con- symbol in the code in a certain well-dened way.
vention used by Visual Studio and is not part of the lan-
guage denition:
/// <summary> /// This class is very classy. /// </sum- 13 Async-await syntax
mary>
This is a feature of C# 5.0 and .NET Frame-
work 4.0.
12.6 XML documentation system
As of .NET Framework 4 there is a task library that
C#'s documentation system is similar to Javas Javadoc, makes it easier to write parallel and multi-threaded ap-
but based on XML. Two methods of documentation are plications through tasks.
currently supported by the C# compiler. C# 5.0 has native language support for asynchrony.
Single-line documentation comments, such as those com- Consider this code that takes advantage of the task library
monly found in Visual Studio generated code, are indi- directly:
cated on a line beginning with // /.
public static class SomeAsyncCode { pub-
public class Foo { // / <summary>A summary of the lic static Task<XDocument> GetContentA-
method.</summary> // / <param name="rstParam">A sync() { HttpClient httpClient = new Http-
description of the parameter.</param> // / <re- Client(); return httpClient.GetStringAsync("www.
marks>Remarks about the method.</remarks> public contoso.com").ContinueWith((task) => {
static void Bar(int rstParam) {} } string responseBodyAsText = task.Result; re-
turn XDocument.Parse(responseBodyAsText);
Multi-line documentation comments, while dened in the }); } } var t = SomeAsync-
version 1.0 language specication, were not supported Code.GetContentAsync().ContinueWith((task) =>
until the .NET 1.1 release.[13] These comments are des- { var xmlDocument = task.Result; }); t.Start();
ignated by a starting forward slash/asterisk/asterisk (/**)
and ending asterisk/forward slash (*/).[14] Here is the same logic written in the async-await syntax:
public class Foo { /** <summary>A summary of the public static class SomeAsyncCode { public
method.</summary> * <param name="rstParam">A static async Task<XDocument> GetContentA-
description of the parameter.</param> * <re- sync() { HttpClient httpClient = new Http-
marks>Remarks about the method.</remarks> */ Client(); string responseBodyAsText = await
public static void Bar(int rstParam) {} } httpClient.GetStringAsync("www.contoso.com");
return XDocument.Parse(responseBodyAsText);
Note there are some stringent criteria regarding white } } var xmlDocument = await SomeAsync-
space and XML documentation when using the forward Code.GetContentAsync(); // The Task will be started on
slash/asterisk/asterisk (/**) technique. call with await.

This code block:


/** * <summary> * A summary of the
method.</summary>*/ 14 Dialects
produces a dierent XML comment than this code 14.1 Spec#
block:[14]
/** * <summary> A summary of the Main article: Spec Sharp
method.</summary>*/
Spec# is a dialect of C# that is developed in parallel with
Syntax for documentation comments and their XML the standard implementation from Microsoft. It extends
18 16 REFERENCES

C# with specication language features and is a possi- Checked exceptions are problematic, because when a
ble future feature to the C# language. It also adds syntax lower-level function adds a new exception type, the whole
for the code contracts API that was introduced in .NET chain of methods using this method at some nested lower
Framework 4.0. Spec# is being developed by Microsoft level must also change its contract. This violates the
Research. open/closed principle.[15]
This sample shows two of the basic structures that are
used when adding contracts to your code.
15 See also
static void Main(string![] args) requires args.Length > 0
{ foreach(string arg in args) { } }
.NET Framework
C Sharp (programming language)
! is used to make a reference type non-nullable, e.g.
you cannot set the value to null. This in contrast of Mono (software)
nullable types which allow value types to be set as Visual C Sharp
null.

requires indicates a condition that must be followed 16 References


in the code. In this case the length of args is not
allowed to be zero or less. [1] Schildt, Herbert, C# 3.0: The Complete Reference

[2] Deitel, Harvey M.; Deitel, Paul J., C# for programmers


14.1.1 Non-nullable types
[3] Constraints on Type Parameters (C# Programming Guide)
Spec# extends C# with non-nullable types that simply [4] Pointer types (C# Programming Guide)
checks so the variables of nullable types that has been set
as non-nullable are not null. If is null then an exception [5] Archer, Part 2, Chapter 4:The Type System
will be thrown. [6] Generics (C# Programming Guide)". Microsoft. Re-
string! input trieved August 7, 2011.

[7] An Introduction to C# Generics. Microsoft.


In use:
[8] Dierences Between C++ Templates and C# Generics.
public Test(string! input) { ... } Microsoft.

[9] An Introduction to C# Generics. Microsoft. January


2005. Retrieved June 18, 2009.
14.1.2 Preconditions [10] In Microsoft MSDN: Constraints on Type Parameters (C#
Programming Guide)
Preconditions are checked before a method is executed.
[11] yield. C# Language Reference. Microsoft. Retrieved
public Test(int i) requires i > 0; { this.i = i; } 2009-04-26.

[12] C# Preprocessor Directives. C# Language Reference.


Microsoft. Retrieved June 18, 2009.
14.1.3 Postconditions [13] Horton, Anson (2006-09-11). C# XML documentation
comments FAQ. Retrieved 2007-12-11.
Postconditions are conditions that are ensured to be cor-
rect when a method has been executed. [14] Delimiters for Documentation Tags. C# Programmers
Reference. Microsoft. January 1, 1970 GMT. Retrieved
public void Increment() ensures i > 0; { i++; } June 18, 2009. Check date values in: |date= (help)

[15] Martin, Robert C. (11 August 2008), 7 Error Handling,


Use Unchecked Exceptions, Clean Code: A Handbook of
14.1.4 Checked exceptions Agile Software Craftsmanship, Prentice Hall International,
ISBN 978-0132350884
Spec# adds checked exceptions like those in Java.
1. Archer, Tom (2001). Inside C#. Microsoft Press.
public void DoSomething() throws SomeException; // ISBN 0-7356-1288-9.
SomeException : ICheckedException { ... }
2. Bart de Smet on Spec#
19

17 External links
C# Language Specication (hyperlinked)

Microsoft .NET Framework


Mono project
20 18 TEXT AND IMAGE SOURCES, CONTRIBUTORS, AND LICENSES

18 Text and image sources, contributors, and licenses


18.1 Text
C Sharp syntax Source: https://en.wikipedia.org/wiki/C_Sharp_syntax?oldid=704096815 Contributors: Damian Yerrick, Timwi,
Greenrd, Phil Boswell, Rursus, Uzume, Mike Rosoft, DerekLaw, Tsumetai, Jeodesic, Hooperbloob, Gpvos, Xhin, Luiscantero, Rjwilmsi,
Dougluce, Crazycomputers, Mathrick, MOF, Visor, StuOfInterest, RussBot, Davidpdx, Bhny, Gaius Cornelius, NickBush24, Welsh,
Wae, Gadget850, Livitup, CWenger, SmackBot, Wlindley, Cush, OrangeDog, MovGP0, Salmar, Het, Danielklein, Acdx, DDima, Sci-
entizzle, JorisvS, Sundstrm, RomanSpa, Loadmaster, Xionbox, Iridescent, Lnatan25, AndrewHowse, Cydebot, Torc2, Ike-bana, Cetinsert,
Tsuji, Magioladitis, VoABot II, NMarkRoberts, Jacobko, D3z, Applrpn, ArgZero, Christopher G Lewis, Realelite, Dispenser, TomyDuby,
Austin512, Skier Dude, Nimh168, Daniel5Ko, Daxx wp, Flatscan, Kwetal, 28bytes, Hqb, Kheldysh, Billinghurst, S.rvarr.S, SieBot,
Gorpik, Jerryobject, Aly89, Svick, Fishnet37222, Tuntable, Grazfather, ClueBot, Supertouch, Mild Bill Hiccup, Doctor It, GFHandel,
Certes, Mitch Ames, Addbot, Btx40, MrOllie, Download, Wlahhn, CountryBot, Yobot, Jim1138, Xqbot, Drilnoth, Almabot, Backpack-
adam, Skywalker363, Setede, FrescoBot, Fortdj33, Sae1962, LittleWink, , NSCoder, Gagundathar Inexplicable, Rapha222, Lesus,
Forbin1, SporkBot, PrescoC, Colejohnson66, ClueBot NG, Snookituation, Snotbot, JGPorteous, Theopolisme, Ynzargu, Jrajav, Dexbot,
Codename Lisa, Softzen, Newmangling, 915Ninja, Monkbot, Samrocca, J.Neill98, Leandropaulino79 and Anonymous: 206

18.2 Images

18.3 Content license


Creative Commons Attribution-Share Alike 3.0

Das könnte Ihnen auch gefallen