User:Sundström/Drafts/C Sharp syntax


 * Main article: C Sharp (programming language)

This article describes the syntax of the C# programming language. The features described are compatible with .NET Framework and Mono.

Identifier
An identifier is the name of an element in the code. There are certain standard naming conventions to follow when selecting names for elements.

An identifier can:
 * start with a "_".
 * contain both upper case and lower case letters.

An identifier cannot:
 * start with a numeral.
 * start with a symbol, unless it is a keyword (check Keywords).
 * have more than 511 chars.

Keywords
Keywords are predefined reserved words with special syntactic meaning. Some of them are only reserved in contextual meaning. Keywords cannot directly be used as identifiers. They can be prefixed with @ for use as identifiers.

Using a keyword as an identifier.

Variables
Variables are identifiers associated with values. They are declared by writing the variable's type and name, and are optionally initialized in the same statement by assigning a value.

Declare

Initialize

Declare & Initialize Multiple variables of the same type can be declared and initialized in one statement.

Type inference

 * This is a feature of C Sharp 3.0.

C# 3.0 introduced type inference, allowing the type specifier of a variable declaration to be replaced by the keyword var, if its actual type can be statically determined from the initializer. This reduces repetition, especially for types with multiple generic type-parameters, and adheres more closely to the DRY principal.

See also
 * Type inference

Constants
Constants are values that are immutable and can not change.

When declaring a local variable or a field with the -keyword as a prefix the value must be given when it is declared. After that it is locked and cannot change anymore. They can either be declared in the context as a field or a local variable. Constants are implicitly static.

This shows all the uses of the keyword.

The  keyword does a similar thing to fields. Like fields marked as  they cannot change when initialized. The difference is that you can choose to initialize it in a constructor. This only work on fields. Read-only fields can either be members of an instance or static class members.

Code blocks
Through out in C# the operators  are used to signify a code block and a new scope. Class members and the body of a method are examples of what can live inside these braces in various contexts.

Inside of method bodies you can use the braces to create new scopes like so:

Program structure
A C# application is consisting of classes and their members. Classes and other types exist in namespaces but can also be nested inside other classes.

-method
Whether it is a console or a graphical interface application the program must have an entrypoint of some sort. The entrypoint of the C# application is the -method. There can only be one and it is a static method which is situated in a class. The method usually returns  and can pass command-line arguments as an array of strings. A Main-method is also allowed to return an integer value if specified.

Namespaces
Namespaces are a part of a type name and they are used to group and/or distinguish names entities from other ones.

A namespace is defined like this:

-statement
The -statement loads a specific namespace from a referenced assembly. It is usually placed in the top (or header) of a code file but it can be placed elsewhere if wanted. Like for instance inside classes.

You can also use the statement to define another name for an existing type. This can simplify your code.

Operator overloading
Some of the existing operators can be overloaded by writing an overload method.

These are the overloadable operators:


 * Assignment operators ( etc.) are combinations of a binary operator and the assignment operator  and will be evaluated using the ordinary operators, which can be overloaded.
 * Cast operators cannot be overloaded, but you can define conversion operators.

See also
 * Array indexing operator is not overloadable, but you can define new indexers.
 * Operator overloading

Conversion operators
The cast operator is not overloadable but you can write a conversion operator method which lives in the target class. Conversion methods can define two varieties of 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 used.

Implicit conversion operator

Explicit conversion operator

If statement
Simple one-line statement:

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

Recommended coding conventions for an if-statement.

Iteration structures
Iteration statements are statements that are repeatedly executed when a given condition is evaluated as true.

For-each loop
The for-each statement is derived from the for-statement and uses the built-in iterators over arrays and collections.

Each item in the give collection will be returned and reachable in the context of the code block. When the block has been executed the next item will be returned until there are no left.

Labels and Goto statement
Labels are given points in code that can be jumped to by using the  statement.

Break statement
The  breaks out of all control statements.

Continue statement
The  breaks out of the current control statement.

Types
C# is a strongly-typed language just like its predecessors C and C++. That means that every variable and constant get a fixed type when they are being declared. There are two kinds of types: value types and reference types.

Structs
Structures are more commonly known as structs. Structs are user-defined value types that are declared using the  keyword. They are very similar to classes but are more suitable for lightweight types. Some important syntactical differences between a  and a   are presented later in this article.

The primitive data types are all structs.

Pre-defined types
Note:   is not a struct and does not count as a primitive.

Enumerations
Enumerated types are types containg a names that represents integral values.

-instances are declared as ordinary variables and they get the default value 0. You can later assign the values contained in the declared enumeration type.

You can increment and decrement -variable to get another value.

See also
 * Enumeration

Classes
Classes are self-describing used-defined reference types.

class
The  class represents an immutable sequence of unicode characters.

Interface
Interfaces are data structures that contains member definitions and not an actual implementation. They are useful when you want to define a contract between members in different types that has different implementations. You can declare definitions for methods, properties and indexers. These must be implemented by a class as public members.

Delegate
C# provides type-safe object-oriented function pointers in the form of delegates. Initializing the delegate with an anonymous method.

See also


 * Delegate

Events
Events are pointers that can point to multiple methods. More exactly they bind method pointers to one identifier. This can therefor be seen as an extension to delegates. They are typically used as triggers in UI development.

They are declared like so:

This is how they are used:

See also


 * Event-driven programming

Nullable types

 * This is a feature of C Sharp 2.0.

Enables value types to allow the value  to be assigned to them.

Pointers
C# has and allows pointers to value types (primitives, enums and structs) in unsafe context: methods and codeblock marked. These are syntactically the same as pointers in C and C++. However, runtime-checking is disabled inside -blocks.

See also
 * Pointer

Dynamic

 * This is a future feature of C Sharp 4.0 and .NET Framework 4.0.

Type  is a feature that enables dynamic runtime lookup to C# in a static manner. Dynamic is a static "type" which exists at runtime.

Boxing and unboxing
Boxing is the operation of converting a value of a value type into a value of a corresponding reference type. Boxing in C# is implicit.

Unboxing is the operation of converting a value of a reference type (previously boxed) into a value of a value type. Unboxing in C# requires an explicit type cast.

Example:

Object-oriented programming (OOP)
C# is a object-oriented programming language.

See also


 * Object-oriented programming

Objects
An object is created with the type as a template and is called an instance of that particular type.

In C# objects are either references or values. No further distinction is made between those in code.

class
All types, even value types in their boxed form, implicitly inherit from the  class which is the ultimate base class of all objects. The class contains the most common methods shared by all objects. Some of these are  and can be overridden.

Some of the members:


 * - Supports comparisons between objects.


 * - Performs cleanup operations before an object is automatically reclaimed. (Default destructor)


 * - Generates a number corresponding to the value of the object to support the use of a hash table.


 * - Gets the Type of the current instance.


 * - Manufactures a human-readable text string that describes an instance of the class

Classes
Classes are fundamentals of an object-oriented language such as C#. They serve as a template for objects. They contain members that store and manipulate data in real-life-like way.

See also
 * Class


 * Structure

Differences between classes and structs
Although classes and structures are similar in both the way they are declared and how they are used there are some significant differences. Classes are reference types and structs value types. A structure is allocated on the stack when it is declared and the variable is bound to its address. It directly contains the value. Classes are different because the memory is allocated as objects on the heap. Variables are rather managed pointers on the stack which points to the objects. They are references.

Structures requires some more than classes. For example you need to explicitly create a default constructor which takes no arguments to initialize the struct and its members. The compiler will create a default one for classes. All fields and properties of as struct must have been initialized before an instance is created. Structs does not have finalizers and cannot inherit from another class like classes do. But they inherit from, that inherits from. Structs are more suitable for smaller constructs of data.

This is a short summary of the differences:

Declaration
A class is declared like so:

Partial class

 * This is a feature of C Sharp 2.0.

A partial class is a class declaration whose code is divided into separate files. The different parts of a partial class must be marked with keyword.

Initialization
Before you can use the members of the class you need to initialize the variable with a reference to a object. To create on you call the appropriate constructor using the  keyword. It has the same name as the class.

For structs it is optional to explicitly call a constructor because the default one is called automatically. You just need to declare it and it gets initialized with standard values.

Object initializers

 * This is a feature of C Sharp 3.0.

Provides a more convenient way of initializing public fields and properties of an object. Constructor calls are optional when there is a default constructor.

Collection initializers

 * This is a feature of C Sharp 3.0.

Collection initializers give an array-like syntax for initializing collections. The compiler will simply generate calls to the Add-method. This works for classes that implement the interface.

Accessing members
Members of both instances and static classes are accessed with the  operator.

Accessing an instance member Instance members can be accessed through the name of a variable.

Accessing a static class member Static members are accessed by using the name of the class or any other type.

Modifiers
Modifiers are keywords used to modify declarations of types and type members. Most notably there is a sub-group containing the access modifiers.


 *   - Specifies that a class only serves as a base class. It must be implemented in an inheriting class.


 *   - Specifies that a variable is a constant value that have to be initialized when it is declared.


 *   - Declare an event.


 *   - Specify that a method signature without a body us a DLL-import.


 *   - Specify that a method or propery declaration is an override of a virtual member or an implementation of a member of an abstract class.


 *   - Declare a field that can only be assigned values as part of the declaration or in a constructor in the same class.


 *   - Specifies that a class cannot be inherited.


 *   - Specifices that a member belongs to the class and not to a specific instance. (see section static)







Access modifiers
The access modifiers set the accessibility of classes, methods and other members. Something marked  can be reached from anywhere. members can only be accessed from inside of the class they are declared inand will be hidden when inherited. Members with the  modifier will be private but accessible when inherited. classes and members will only be accessible from the inside of the declaring assembly.

Classes and members are implicitly  if they do not have an access modifier.

The  defines that a member belongs to the class and not a specific object. Classes marked static are only allowed to contain static members. Static members are sometimes referred to as class members.

Constructors
A constructor is a special method that is called when a object is going to be initialized. Its purpose is to initialize the members of the object. The main differences between constructors and ordinary methods are that constructors are named after the class and does not return anything. They may take parameters as any method.

Constructors can be,   or.

See also
 * Constructor

Destructor
The destructor is called when the object is being collected by the garbage collector to perform some manual clean-up. There is a default destructor method called  that can be overridden by declaring your own.

The syntax is similar to the one of constructors. The difference is that the name is preceded by a ~ and it cannot contain any parameters. There cannot be more than one destructor.

Finalizers are always.

See also
 * Destructor

Methods
You simply call the method by using.

See also


 * Method

and parameters
You can explicitly make arguments be passed by reference when calling a method with parameters preceded by keywords  or. These managed pointers comes in handy when passing value type variables that you want to be modified inside the method by reference. The main difference between the two is that an -parameter must be assigned when the method returns.

Optional parameters

 * This is a future feature of C Sharp 4.0.

C# 4.0 introduces optional parameters with default values as seen in C++. For example:

In addition, to complement optional parameters, it is possible to explicitly specify parameter names in method calls, allowing to selectively pass any given subset of optional parameters for a method. The only restriction is that named parameters must be placed after the unnamed parameters. Parameter names can be specified for both optional and required parameters, and can be used to improve readability or arbitrarily reorder arguments in a call. For example:

Optional parameters make interoperating with COM easier. Previously, C# had to pass in every parameter in the method of the COM component, even those that are optional. For example:

With support for optional parameters, the code can be shortened as

A feature of C# is the abillity to call native code. You simply declare a method signature without a body and mark it as. You also need to add the -attribute to reference the DLL-file you want.

Fields
Fields, or class variables, can be declares inside the class body to store data. It is considered good practice to keep a field private and declare a property to access it.

Fields can initialized directly when declared.

Modifiers for fields:


 * - Makes the field a static member.


 * - Allows the field to be initialized only once in a constructor.
 * - Makes the field a constant.


 * - Makes the field public.
 * - Makes the field private.
 * - Makes the field protected.

Properties
Properties bring field-like syntax and combine them with the power of methods. A property can have two accessors:  and.

Modifiers for properties:


 * - Makes the property a static member.


 * - Makes the property public.
 * - Makes the property private.
 * - Makes the property protected.

Modifiers for property accessors:


 * - Makes the accessor public.
 * - Makes the accessor private.
 * - Makes the accessor protected.

Automatic properties

 * This is a feature of C Sharp 3.0.

A feature of C# 3.O is auto-implemented properties. You define accessors without bodies and the compiler will generate a backingfield and the necessary code for the accessors.

Indexers
Indexers add array-like indexing capabilities to objects. They are implemented in a way similar to properties.

Inheritance
Classes in C# may only inherit from one classes. A class may derive from any class that is not marked as.

See also
 * Inheritance

Methods marked  provide an implementation but it can be overridden by the inheritors by using the  -keyword.

Abstract classes are classes that only serve as templates and you can not initialize a object of that type. Otherwise it is just like an ordinary class.

There may be abstract members too. Abstract members are members of abstract classes that do not have any implementation. They must be overridden by the class that inherits the member.

The  modifier can be combined with the others as an optional modifier for classes to make them in-inheritable.

Interfaces
Interfaces are data structures that contains member definitions and not an actual implementation. They are useful when you want to define a contract between members in different types that has different implementations. You can declare definitions for methods, properties and indexers. These must be implemented by a class as public members.

Implementing an interface
An interface is implemented by a class or extended by another interface in the same way you derive a class from another class using the -notation.

Note: The properties in the class that extends  are auto-implemented by the compiler. Both gets a backingfield.

Here is a interface that extends two interfaces.

Generics

 * This is a feature of C Sharp 2.0 and .NET Framework 2.0.

Generics, or parameterized types, orparametric polymorphism is a .NET 2.0 feature supported by C#. Unlike C++ templates, .NET parameterized types are instantiated at runtime 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 such as type constraints on generic parameters by use of interfaces. On the other hand, C# does not support non-type generic parameters. Unlike generics in Java, .NET generics use reification to make parameterized types first-class objects in the CLI Virtual Machine, which allows for optimizations and preservation of the type information.

See also


 * Generic programming

Type-parameters
Type-parameters are names used in place of concrete types when defining a new generic. They may be associated with classes or methods by placing the type parameter in angle brackets < >. When instantiating (or calling) a generic, you can then substitute a concrete type for the type-parameter you gave in its declaration. Type paremeters may be constrained by use of the where keyword and a constraint specification, any of the six comma separated constraints may be used:

Covariance and contravariance

 * This is a future feature of C Sharp 4.0 and .NET Framework 4.0.

Generic interfaces and delegates can have their type parameters marked as covariant or contravariant, using keywords  and , respectively. These declarations are then respected for type conversions, both implicit and explicit, and both compile-time and run-time. For example, the existing interface  has been redefined as follows:

Therefore, any class that implements  for some class   is also considered to be compatible with   for all classes and interfaces   that   extends, directly, or indirectly. In practice, it makes it possible to write code such as:

For contravariance, the existing interface  has been redefined as follows: Therefore, any class that implements  for some class   is also considered to be compatible with   for all classes and interfaces   that are extended from. It makes it possible to write code such as:

See also
 * Covariance and contravariance

Generic classes
Classes and structs can be generic.

Enumerators
An enumerator is an iterator. Enumerators are typically obtained by calling the  method of an object implementing the  interface. Container classes typically implement this interface. However, the foreach statement inC# can operate on any object providing such a method, even if it doesn't implement. Both interfaces were expanded into generic versions in .NET 2.0.

The following shows a simple use of iterators in C# 2.0:

Generator functionality

 * This is a feature of C Sharp 2.0.

The .NET 2.0 Framework allowed C# to introduce an iterator that provides generatorfunctionality, using a  construct similar to   in Python. With a, the function automatically keeps its state during the iteration.

LINQ

 * This is a feature of C Sharp 3.0 and .NET Framework 3.0.
 * Main article: LINQ

LINQ, short for Language Integrated Queries, is a .NET Framework feature which simplifies the handling of data. Mainly it adds support that allows you to query arrays, collections and databases. It also introduces binders that makes it easier to access to databases and their data.

Query syntax
The LINQ query syntax was introduces C# 3.0 and let you write SQL-like queries in C#.

The statements are compiled into method calls on the object of the type that ultimately must implement.

Anonymous methods
Anonymous methods, or in their present form more commonly referred to as "lambda expressions", is a feature which allows you to write inline closure-like functions in your code.

There are various of ways to create anonymous methods. Prior to C# 3.0 there was limited support by using delegates.

See also


 * Anonymous function
 * Closure

Anonymous delegates

 * This is a feature of C Sharp 2.0.

Anonymous delegates are declared in code.

Lambda expressions

 * This is a feature of C Sharp 3.0.

Lambda expressions provide a simple syntax for inline functions that are similar to closures. Functions with parameters infer the type of the parameters if other is not explicitly specified.

Alternative syntax: Lambda expressions can be passed as arguments in method calls.

Lambda expression are essentially compiler generated methods that are passed via delegates.

Anonymous types

 * This is a feature of C Sharp 3.0.

Anonymous types are nameless classes that are generated by the compiler. They are only consumable and yet very useful in a scenario like where you have a LINQ query which returns an object on  and you just want to return some specific values. Then you can define a anonymous type containing auto-generated read-only fields for the values.

When instantiating another anonymous type declaration with the same signature the type is automatically inferred by the compiler.

Extension methods

 * This is a feature of C Sharp 3.0.

Extension methods are a form of syntactic sugar providing the illusion of adding new methods to the existing class outside its definition. In practice, an extension method is a static method that is callable as if it was an instance method; the receiver of the call is bound to the first parameter of the method, decorated with keyword :

See also


 * Decorator pattern

Attributes
Attributes are entities of data that is stored as metadata in the compiled assembly. An attribute can be added to types and members like properties and methods.

The .NET Framework comes with predefined attributes that can be used. Some of them serve an important role at runtime while some is just for syntactic decoration in code like. It does only mark that it is a compiler generated element. You can create your own if needed and/or wanted.

An attribute is essentially a class which inherits from the  class. By convention attribute classes end with "Attribute" in their name. This will not be required when using it.

Showing the attribute in use using the optional constructor parameters.

Preprocessor
C# features "preprocessor directives" (though it does not have an actual preprocessor) based on the C preprocessor that allow programmers to define symbolsbut not macros. Conditionals such as,  , and   are also provided. Directives such as  give hints to editors for code folding.

Code comments
C# utilizes a double forward slash to indicate the rest of the line is a comment.

Multi-line comments can be indicated by a starting forward slash/asterisk and ending asterisk/forward slash.

XML documentation system
C#'s documentation system is similar to Java's Javadoc, but based on XML. Two methods of documentation are currently supported by the C# compiler.

Single-line documentation comments, such as those commonly found in Visual Studio generated code, are indicated on a line beginning with.

Multi-line documentation comments, while defined in the version 1.0 language specification, were not supported until the .NET 1.1 release. These comments are designated by a starting forward slash/asterisk/asterisk and ending asterisk/forward slash.

Note there are some stringent criteria regarding white space and XML documentation when using the forward slash/asterisk/asterisk technique.

This code block:

produces a different XML comment than this code block:

Syntax for documentation comments and their XML markup is defined in a non-normative annex of the ECMA C# standard. The same standard also defines rules for processing of such comments, and their transformation to a plain XML document with precise rules for mapping of CLI identifiers to their related documentation elements. This allows any C# IDE or other development tool to find documentation for any symbol in the code in a certain well-defined way.

Spec#

 * Main article: Spec Sharp

Spec# is the name of a syntactic extension and a possible future feature to the C# language. It adds syntax for the code contracts API that is going to be introduced in .NET Framework 4.0. Spec# is being developed by Microsoft Research.

This example shows two of the basic structures that is used when adding contracts to your code.


 * ! is used to make a reference type non-nullable, e.g. you cannot set the value to null. This in contrast of nullable types which allows value types to be set as null.


 * requires indicates a condition that must be followed in the code. In this case the length of args is not allowed to be zero or less.