Beruflich Dokumente
Kultur Dokumente
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: _
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)
contain @ sign in between or at the end 1.3.1 Local variable type inference
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() { }
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) ... ;
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
do { } while (i == true);
4.3.2 break statement
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; };
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
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
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.
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)
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:
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
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>(); } }
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 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.2 Type-parameters
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# 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.
17 External links
C# Language Specication (hyperlinked)
18.2 Images