C Sharp syntax
Encyclopedia
- Main article: C Sharp (programming language)
This article describes the syntax of the C# programming language
Programming language
A programming language is an artificial language designed to communicate instructions to a machine, particularly a computer. Programming languages can be used to create programs that control the behavior of a machine and/or to express algorithms precisely....
. The features described are compatible with .NET Framework
.NET Framework
The .NET Framework is a software framework that runs primarily on Microsoft Windows. It includes a large library and supports several programming languages which allows language interoperability...
and Mono
Mono (software)
Mono, pronounced , is a free and open source project led by Xamarin to create an Ecma standard compliant .NET-compatible set of tools including, among others, a C# compiler and a Common Language Runtime....
.
Identifier
An identifier is the name of an element in the codeSource code
In computer science, source code is text written using the format and syntax of the programming language that it is being written in. Such a language is specially designed to facilitate the work of computer programmers, who specify the actions to be performed by a computer mostly by writing source...
. There are certain standard naming conventions
Naming conventions (programming)
In computer programming, a naming convention is a set of rules for choosing the character sequence to be used for identifiers which denote variables, types and functions etc...
to follow when selecting names for elements.
An identifier can:
- start with a "_".
- contain both upper case and lower case Unicode letters. Case is significant.
An identifier cannot:
- start with a numeral.
- start with a symbol, unless it is a keyword (check Keywords).
- have more than 511 charsCharacter (computing)In computer and machine-based telecommunications terminology, a character is a unit of information that roughly corresponds to a grapheme, grapheme-like unit, or symbol, such as in an alphabet or syllabary in the written form of a natural language....
.
Keywords
KeywordsKeyword (computer programming)
In computer programming, a keyword is a word or identifier that has a particular meaning to the programming language. The meaning of keywords — and, indeed, the meaning of the notion of keyword — differs widely from language to language....
are predefined reserved words with special syntactic meaning. The language has two types of keyword — contextual and reserved. The reserved keywords such as or may only be used as keywords. The contextual keywords such as or are only treated as keywords in certain situations. If an identifier is needed which would be the same as a reserved keyword, it may be prefixed by the @ character to distinguish it. This facilitates reuse of .NET
.NET Framework
The .NET Framework is a software framework that runs primarily on Microsoft Windows. It includes a large library and supports several programming languages which allows language interoperability...
code written in other languages.
C# keywords, reserved words | |||
---|---|---|---|
2 | |||
2 | |||
2 | |||
2 | |||
2 | |||
2 | |||
2 | |||
2 | |||
2 | 1 | ||
1, 2 These are not actually keywords, thus (unlike actual keywords) it is possible to define variables and types using these names, but they act like keywords in certain new language constructs introduced in C# 2.0(1) and 3.0(2). |
Using a keyword as an identifier:
Literals
Integers | |
---|---|
hexadecimal Hexadecimal In mathematics and computer science, hexadecimal is a positional numeral system with a radix, or base, of 16. It uses sixteen distinct symbols, most often the symbols 0–9 to represent values zero to nine, and A, B, C, D, E, F to represent values ten to fifteen... |
|
decimal Decimal The decimal numeral system has ten as its base. It is the numerical base most widely used by modern civilizations.... |
|
Floating-point values | |
float | |
double | |
Dates | |
date | |
Characters | |
char | |
Strings | |
String | , |
Characters escapes in strings | |
Unicode Unicode Unicode is a computing industry standard for the consistent encoding, representation and handling of text expressed in most of the world's writing systems... character |
followed by the hexadecimal unicode code point |
Tab | |
Backspace Backspace Backspace is the keyboard key that originally pushed the typewriter carriage one position backwards, and in modern computer displays moves the cursor one position backwards, deletes the preceding character, and shifts back the text after it by one position.... |
|
Carriage return Carriage return Carriage return, often shortened to return, refers to a control character or mechanism used to start a new line of text.Originally, the term "carriage return" referred to a mechanism or lever on a typewriter... |
|
Form feed | |
Backslash Backslash The backslash is a typographical mark used mainly in computing. It was first introduced to computers in 1960 by Bob Bemer. Sometimes called a reverse solidus or a slosh, it is the mirror image of the common slash.... |
|
Single quote | |
Double quote | |
Line feed |
Variables
VariablesVariable (programming)
In computer programming, a variable is a symbolic name given to some known or unknown quantity or information, for the purpose of allowing the name to be used independently of the information it represents...
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# 3.0C Sharp 3.0The programming language C# version 3.0 was released on 19 November 2007 as part of .NET Framework 3.5. It includes new features inspired by functional programming languages such as Haskell and ML, and is driven largely by the introduction of the Language Integrated Query pattern to the Common...
.
C# 3.0 introduced type inference, allowing the type specifier of a variable declaration to be replaced by the keyword , 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
Dry
Dry or dryness may refer to:* Lack of water* Prohibiting alcohol * Dryness , the lack of sugar in a drink, especially an alcoholic one * Dryness * Dryness...
principle.
See also
- Type inferenceType inferenceType inference refers to the automatic deduction of the type of an expression in a programming language. If some, but not all, type annotations are already present it is referred to as type reconstruction....
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. 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 once initialized. The difference is that you can choose to initialize them in a constructor. This only works on fields. Read-only fields can either be members of an instance or static class members.
Code blocks
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 consists 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 in a class. The method usually returns and is passed 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 named 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, e.g. inside classes.You can also use the statement to define another name for an existing namespace or type. This is sometimes useful when names are too long and less readable.
Operators
Operator category | Operators |
---|---|
Arithmetic | , , , , |
Logical (boolean and bitwise) | , , , , , , , , |
String concatenation | |
Increment, decrement | , |
Shift | , |
Relational | , , , , , |
Assignment |
|-
|Member access
|
|-
|Indexing
|,
|-
|Cast
|,
|-
|Conditional
|,
|-
|Delegate concatenation and removal
|,
|-
|Object creation
|
|-
| Type information
|
|-
|Overflow exception control
|
|-
|Indirection and Address
|, , ,
|}
Operator overloading
Some of the existing operators can be overloaded by writing an overload method.These are the overloadable operators:
Operators | |
---|---|
, , , , , , , | Unary operators |
, , , , , , , , , | Binary operators |
, != , , , <= , >= |
Comparison operators, must be overloaded in pairs |
- 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.
- Array indexing operator is not overloadable, but you can define new indexers.
See also
- Operator overloadingOperator overloadingIn object oriented computer programming, operator overloading—less commonly known as operator ad-hoc polymorphism—is a specific case of polymorphism, where different operators have different implementations depending on their arguments...
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
operator
The operator will attempt to do a silent cast to a given type. If it succeeds it will return the object as the new type, if it fails it will return a null reference.Null coalesce operator
The followingIs shorthand for
Meaning that if the content of variable is not null, that content will be returned, otherwise the content of variable is returned.
One can also have nullable scalar types such as
(Both new in C Sharp 2.0
C Sharp 2.0
The programming language C# introduces several new features in version 2.0 . These include:- Partial class :...
.)
Control structures
C# inherits most of the control structures of C/C++ and also adds new ones like the statement.
Conditional structures
These structures control the flow of the program through given conditions.statement
The 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.Simple one-line statement:
Multi-line with else-block (without any braces):
Recommended coding conventions for an if-statement.
statement
The construct serves as a filter for different values. Each value leads to a "case". It is not allowed to fall through cases and therefore the use of the keyword is required to end a case (the exception to this is if there is an unconditional in a "case" block). Many cases may lead to the same code though. The default case handles all the other cases not handled by the construct.Iteration structures
Iteration statements are statements that are repeatedly executed when a given condition is evaluated as true.loop
loop
The loop consists of three parts: declaration, condition and increment. Any of them can be left out as they are optional.Is equivalent to this code represented with a statement.
loop
The statement is derived from the statement and makes use of a certain pattern described in C#'s language specification in order to obtain and use an enumerator of elements to iterate over.Each item in the given 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 items remaining.
Jump statements
Jump statements are inherited from C/C++ and ultimately assembly languages through it. They simply represent the jump-instructions of an assembly language that controls the flow of a program.Labels and statement
Labels are given points in code that can be jumped to by using the statement.The statement can be used in statements to jump from one case to another or to fall through from one case to the next.
statement
The statement breaks out of the closest loop or statement. Execution continues in the statement after the terminated statement, if any.statement
The statement discontinues the current iteration of the current control statement and begins the next iteration.The loop in the code above reads characters by calling , skipping the statements in the body of the loop if the characters are spaces.
Exception handling
C# has a neat way of handling runtime exceptions that is inherited from Java and C/C++ through it.The base class library has a class called from which all exceptions are derived. An -object contains all the information about a specific exception and also the inner exceptions that were caused.
The programmer may define their own exceptions by deriving from the class.
An exception can be thrown this way:
statements
Exceptions are managed within blocks.The statements within the block are executed, and if any of them throws an exception, execution of the block is discontinued and the exception is handled by the block. There may be multiple blocks, in which case the first block with an exception variable whose type matches the type of the thrown exception is executed.
If no block matches the type of the thrown exception, the execution of the outer block (or method) containing the statement is discontinued, and the exception is passed up and outside the containing block (or method). The exception is propagated upwards through the call stack
Call stack
In computer science, a call stack is a stack data structure that stores information about the active subroutines of a computer program. This kind of stack is also known as an execution stack, control stack, run-time stack, or machine stack, and is often shortened to just "the stack"...
until a matching block is found within one of the currently active methods. If the exception propagates all the way up to the top-most method without a matching block being found, the entire program is terminated and a textual description of the exception is written to the standard output stream.
The statements within the block are always executed after the and blocks, whether or not an exception was thrown. Such blocks are useful for providing clean-up code that is guaranteed to always be executed.
The and blocks are optional, but at least one or the other must be present following the block.
Types
C# is a statically typed language like 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.
Value types
Instances of value types reside on the stack, i.e. they are bound to their variables. If you declare a variable for a value type the memory gets allocated directly. If the variable gets out of scope the object is destroyed with it.Structures
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
These are the primitive datatypes.
Primitive Types | |||||
---|---|---|---|---|---|
Type Name | BCL Base Class Library The Base Class Library is a standard library available to all languages using the .NET Framework. .NET includes the BCL in order to encapsulate a large number of common functions, such as file reading and writing, graphic rendering, database interaction, and XML document manipulation, which makes... Equivalent |
Value | Range | Size | Default Value |
integer | −128 through +127 | 8-bit (1-byte) | |||
integer | −32,768 through +32,767 | 16-bit (2-byte) | |||
integer | −2,147,483,648 through +2,147,483,647 | 32-bit (4-byte) | |||
integer | −9,223,372,036,854,775,808 through +9,223,372,036,854,775,807 |
64-bit (8-byte) | |||
unsigned integer | 0 through 255 | 8-bit (1-byte) | |||
unsigned integer | 0 through 65,535 | 16-bit (2-byte) | |||
unsigned integer | 0 through 4,294,967,295 | 32-bit (4-byte) | |||
unsigned integer | 0 through 18,446,744,073,709,551,615 | 64-bit (8-byte) | |||
signed decimal number | −7.9228162514264337593543950335 through +7.9228162514264337593543950335 |
128-bit (16-byte) | |||
floating point number | ±1.401298E−45 through ±3.402823E+38 | 32-bit (4-byte) | |||
floating point number | ±4.94065645841246E−324 through ±1.79769313486232E+308 |
64-bit (8-byte) | |||
Boolean | or | 8-bit (1-byte) | |||
single Unicode character | through | 16-bit (2-byte) |
Note: is not a struct and is not a primitive type.
Enumerations
Enumerated types are named values representing integer values.instances are declared as ordinary variables and are initialized by default to zero. They can be assigned or initialized to the named values defined by the enumeration type.
types variables are basically integer values. That means that addition and subtraction between variables of the same type is allowed without any specific cast but multiplication and division is somewhat more risky and requires it explicitly. Casts are also required to and from integer types. It will however throw an exception if the value is not allowed.
Values can be combined using the bitwise-OR operator, .
See also
- Enumeration (programming)
Reference types
Variables created for reference types are typed managed references. When the constructor is called an object is created on the heap and a reference is assigned to the variable. When a variable of an object gets out of scope the reference is broken and when there are no references left the object gets marked as garbage. The garbage collector will then soon collect and destroy it.A reference variable is when it does not reference any object.
Arrays
An array type is a reference type that refers to a space containing one or more elements of a certain type. All array types derive from a common base class, . Each element is referenced by its index just like in C++ and Java.An array in C# is what would be called a dynamic array
Dynamic array
In computer science, a dynamic array, growable array, resizable array, dynamic table, or array list is a random access, variable-size list data structure that allows elements to be added or removed...
in C++.
Initializers
Array initializers provide convenient syntax for initialization of arrays.
Multi-dimensional arrays
Arrays can have more than one dimension, for example 2 dimensions to represent a grid.
See also
- Jagged array
Classes
Classes are self-describing user-defined reference types. Essentially all types in the .NET Framework are classes, including structs and enums, that are compiler generated classes.class
The class, or simply , represents an immutable sequence of unicode characters .
Actions performed on a string will always return a new string.
The class can be used when a mutable "string" is wanted.
Interface
Interfaces are data structures that contain member definitions with no actual implementation. They are useful for when you want to define a contract between members in different types that have different implementations. You can declare definitions for methods, properties, and indexers. These must be implemented by a class as public members.Delegates
C# provides type-safe object-oriented function pointers in the form of delegates.Initializing the delegate with an anonymous method.
See also
- Delegate (.NET)Delegate (.NET)A delegate is a form of type-safe function pointer used by the .NET Framework. Delegates specify a method to call and optionally an object to call the method on. They are used, among other things, to implement callbacks and event listeners....
Events
Events are pointers that can point to multiple methods. More exactly they bind method pointers to one identifier. This can therefore be seen as an extension to delegatesDelegate (.NET)
A delegate is a form of type-safe function pointer used by the .NET Framework. Delegates specify a method to call and optionally an object to call the method on. They are used, among other things, to implement callbacks and event listeners....
. They are typically used as triggers in UI development. The form used in C# and the rest of the Common Language Infrastructure
Common Language Infrastructure
The Common Language Infrastructure is an open specification developed by Microsoft and standardized by ISO and ECMA that describes the executable code and runtime environment that form the core of the Microsoft .NET Framework and the free and open source implementations Mono and Portable.NET...
is based on that in the classic Visual Basic
Visual Basic
Visual Basic is the third-generation event-driven programming language and integrated development environment from Microsoft for its COM programming model...
.
An event requires an accompanied event handler that is made from a special delegate that in a platform specific library like in Windows Presentation Foundation
Windows Presentation Foundation
Developed by Microsoft, the Windows Presentation Foundation is a computer-software graphical subsystem for rendering user interfaces in Windows-based applications. WPF, previously known as "Avalon", was initially released as part of .NET Framework 3.0. Rather than relying on the older GDI...
and Windows Forms
Windows Forms
Windows Forms is the name given to the graphical application programming interface included as a part of Microsoft .NET Framework, providing access to native Microsoft Windows interface elements by wrapping the extant Windows API in managed code...
usually takes two parameters: sender and the event arguments. The type of the event argument-object derive from the EventArgs class that is a part of the CLI base library.
Once declared in its class the only way of invoking the event is from inside of the owner. A listener method may be implemented outside to be triggered when the event is fired.
See also
- Event-driven programmingEvent-driven programmingIn computer programming, event-driven programming or event-based programming is a programming paradigm in which the flow of the program is determined by events—i.e., sensor outputs or user actions or messages from other programs or threads.Event-driven programming can also be defined as an...
Nullable types
- This is a feature of C Sharp 2.0C Sharp 2.0The programming language C# introduces several new features in version 2.0 . These include:- Partial class :...
.
Nullable types were introduced in C Sharp 2.0 firstly to enable value types to be when working with a database.
In reality this is the same as using the struct.
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.Structs are required only to be pure structs with no members of a managed reference type, e.g. a string or any other class.
In use:
See also
- Pointer (programming)
Dynamic
- This is a feature of C Sharp 4.0C Sharp 4.0C# 4.0 is the latest version of the C# programming language, which was released on April 11, 2010. Microsoft has released the 4.0 runtime and development environment Visual Studio 2010...
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:
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 syntactical 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.Classes inherit either directly or indirectly through another base class.
Members
Some of the members of the class:
- Supports comparisons between objects.
- Performs cleanup operations before an object is automatically reclaimed. (Default destructor)
- Gets the number corresponding to the value of the object to support the use of a hash table.
- Gets the Type of the current instance.
- Creates a human-readable text string that describes an instance of the class. Usually it returns the name of the type.
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 a real-life-like way.See also
- Class (computer science)Class (computer science)In object-oriented programming, a class is a construct that is used as a blueprint to create instances of itself – referred to as class instances, class objects, instance objects or simply objects. A class defines constituent members which enable these class instances to have state and behavior...
- Structure (computer science)
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 point to the objects. They are references.Structures require 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 a struct must have been initialized before an instance is created. Structs do not have finalizers and cannot inherit from another class like classes do. However, they inherit from , that inherits from . Structs are more suitable for smaller constructs of data.
This is a short summary of the differences:
Default constructor | Finalizer | Member initialization | Inheritance | |
---|---|---|---|---|
Classes | not required (auto generated) | yes | not required | yes (if base class is not ) |
Structs | required (not auto generated) | no | required | not supported |
Declaration
A class is declared like this:Partial class
- This is a feature of C Sharp 2.0C Sharp 2.0The programming language C# introduces several new features in version 2.0 . These include:- Partial class :...
.
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 an object. To create it 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.0C Sharp 3.0The programming language C# version 3.0 was released on 19 November 2007 as part of .NET Framework 3.5. It includes new features inspired by functional programming languages such as Haskell and ML, and is driven largely by the introduction of the Language Integrated Query pattern to the Common...
.
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.0C Sharp 3.0The programming language C# version 3.0 was released on 19 November 2007 as part of .NET Framework 3.5. It includes new features inspired by functional programming languages such as Haskell and ML, and is driven largely by the introduction of the Language Integrated Query pattern to the Common...
.
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.
Accessing a member through a pointer
In unsafe code, members of a value (struct type) referenced by a pointer are accessed with the operator just like in C and C++.
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 has to be initialized when it gets declared. - Declare an event. - Specify that a method signature without a body uses a DLL-import. - Specify that a method or property 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. - Specifies that a member belongs to the class and not to a specific instance. (see section static) - Specifies an unsafe context, which allows the use of pointers. - Specifies that a method or property declaration can be overridden by a derived class. - Specifies a field which may be modified by an external process and prevents an optimizing compiler from modifying the use of the field.
Access modifiers
The access modifiers, or inheritance 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 in and will be hidden when inherited. Members with the modifier will be , but accessible when inherited. classes and members will only be accessible from the inside of the declaring assembly.
Classes and structs are implicitly and members are implicitly if they do not have an access modifier.
Unnested types | Members (incl. Nested types) | |
---|---|---|
yes | yes | |
no | yes (default) | |
no | yes | |
yes (default) | yes | |
no | yes |
The modifier states that a member belongs to the class and not to a specific object. Classes marked static are only allowed to contain static members. Static members are sometimes referred to as class members since they apply to the class as a whole and not to its instances.
Constructors
A constructor is a special method that is called when an object is going to be initialized. Its purpose is to initialize the members of the object. The main differences between constructors andordinary methods are that constructors are named after the class and do not return anything. They may take parameters as any method.
Constructors can be , , or .
See also
- Constructor (computer science)Constructor (computer science)In object-oriented programming, a constructor in a class is a special type of subroutine called at the creation of an object. It prepares the new object for use, often accepting parameters which the constructor uses to set any member variables required when the object is first created...
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 (computer science)Destructor (computer science)In object-oriented programming, a destructor is a method which is automatically invoked when the object is destroyed...
Methods
Like in C and C++ there are functions that group reusable code. The main difference is that functions just like in Java have to reside inside of a class. A function is therefore called a method. A method has a return value, a name and usually some parameters initialized when it is called with some arguments. It can either belong to an instance of a class or be a static member.A method is called using notation on a specific variable, or as in the case of static methods, the name of a type.
See also
- Method (computer science)Method (computer science)In object-oriented programming, a method is a subroutine associated with a class. Methods define the behavior to be exhibited by instances of the associated class at program run time...
and parameters
One can explicitly make arguments be passed by reference when calling a method with parameters preceded by keywords or . These managed pointers come 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 have been assigned within the method by the time the method returns, while ref need not assign a value.
Optional parameters
- This is a feature of C Sharp 4.0C Sharp 4.0C# 4.0 is the latest version of the C# programming language, which was released on April 11, 2010. Microsoft has released the 4.0 runtime and development environment Visual Studio 2010...
.
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 ability to call native code. A method signature is simply declared without a body and is marked as . The attribute also needs to be added to reference the desired DLL file.
Fields
Fields, or class variables, can be declared 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 be initialized directly when declared.
Modifiers for fields:
- Makes the field a constant. - Makes the field private (default). - Makes the field protected. - Makes the field public. - Allows the field to be initialized only once in a constructor. - Makes the field a static member.
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 private (default). - Makes the property protected. - Makes the property public. - Makes the property a static member.
Modifiers for property accessors:
- Makes the accessor private. - Makes the accessor protected. - Makes the accessor public.
The default modifiers for the accessors are inherited from the property. Note that the accessor's modifiers can only be equal or more restrictive than the property's modifier.
Automatic properties
- This is a feature of C Sharp 3.0C Sharp 3.0The programming language C# version 3.0 was released on 19 November 2007 as part of .NET Framework 3.5. It includes new features inspired by functional programming languages such as Haskell and ML, and is driven largely by the introduction of the Language Integrated Query pattern to the Common...
.
A feature of C# 3.0 is auto-implemented properties. You define accessors without bodies and the compiler will generate a backing field and the necessary code for the accessors.
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 class. A class may derive from any class that is not marked as .See also
- Inheritance (computer science)Inheritance (computer science)In object-oriented programming , inheritance is a way to reuse code of existing objects, establish a subtype from an existing object, or both, depending upon programming language support...
Methods marked provide an implementation, but they can be overridden by the inheritors by using the keyword.
The implementation is chosen by the actual type of the object and not the type of the variable.
When overloading a non-virtual method with another signature, the keyword may be used. The used method will be chosen by the type of the variable instead of the actual type of the object.
This demonstrates the case:
Abstract classes are classes that only serve as templates and you can not initialize an 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 uninheritable.
Interfaces
Interfaces are data structures that contain member definitions and not actual implementation. They are useful when you want to define a contract between members in different types that have different implementations. You can declare definitions for methods, properties, and indexers. An interface can either be implicitly or explicitly implemented.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.Implicit implementation
When implicitly implementing an interface the members of the interface have to be .
In use:
Explicit implementation
You can also explicitly implement members. The members of the interface that are explicitly implemented by a class are accessible only when the object is handled as the interface type.
In use:
Note: The properties in the class that extends are auto-implemented by the compiler. Both get a backingfield.
Extending multiple interfaces
Interfaces and classes are allowed to extend multiple interfaces.
Here is an interface that extends two interfaces.
Interfaces vs . Abstract classes
Interfaces and abstract classes are similar. The following describes some important differences:- An abstract class may have member variables as well as non-abstract methods or properties. An interface cannot.
- A class or abstract class can only inherit from one class or abstract class.
- A class or abstract class may implement one or more interfaces.
- An interface can only extend other interfaces.
- An abstract class may have non-public methods and properties (also abstract ones). An interface can only have public members.
- An abstract class may have constants, static methods and static members. An interface cannot.
- An abstract class may have constructors. An interface cannot.
Generics
- This is a feature of C Sharp 2.0C Sharp 2.0The programming language C# introduces several new features in version 2.0 . These include:- Partial class :...
and .NET Framework 2.0.
Generics
Generic programming
In a broad definition, generic programming is a style of computer programming in which algorithms are written in terms of to-be-specified-later types that are then instantiated when needed for specific types provided as parameters...
, or parameterized types, or parametric 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
Reification (computer science)
Reification is the process by which an abstract idea about a computer program is turned into an explicit data model or other object created in a programming language. A computable/addressable object — a resource — is created in a system as a proxy for a non computable/addressable object...
to make parameterized types first-class objects in the Common Language Infrastructure
Common Language Infrastructure
The Common Language Infrastructure is an open specification developed by Microsoft and standardized by ISO and ECMA that describes the executable code and runtime environment that form the core of the Microsoft .NET Framework and the free and open source implementations Mono and Portable.NET...
(CLI) Virtual Machine, which allows for optimizations and preservation of the type information.
See also
- Generic programmingGeneric programmingIn a broad definition, generic programming is a style of computer programming in which algorithms are written in terms of to-be-specified-later types that are then instantiated when needed for specific types provided as parameters...
Generic classes
Classes and structs can be generic.Generic methods
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 parameters may be constrained by use of the keyword and a constraint specification, any of the six comma separated constraints may be used:Constraint | Explanation |
---|---|
type parameter must be a value type | |
type parameter must be a reference type | |
type parameter must have a constructor with no parameters (must appear last) | |
type parameter must inherit from | |
type parameter must be, or must implement this interface | |
naked type parameter constraint |
Covariance and contravariance
- This is a feature of C Sharp 4.0C Sharp 4.0C# 4.0 is the latest version of the C# programming language, which was released on April 11, 2010. Microsoft has released the 4.0 runtime and development environment Visual Studio 2010...
and .NET Framework 4.0.
Generic
Generic programming
In a broad definition, generic programming is a style of computer programming in which algorithms are written in terms of to-be-specified-later types that are then instantiated when needed for specific types provided as parameters...
interfaces and delegates can have their type parameters marked as covariant
Covariance and contravariance (computer science)
Within the type system of a programming language, covariance and contravariance refers to the ordering of types from narrower to wider and their interchangeability or equivalence in certain situations ....
or contravariant
Covariance and contravariance (computer science)
Within the type system of a programming language, covariance and contravariance refers to the ordering of types from narrower to wider and their interchangeability or equivalence in certain situations ....
, 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 contravarianceCovariance and contravarianceIn multilinear algebra and tensor analysis, covariance and contravariance describe how the quantitative description of certain geometric or physical entities changes with a change of basis from one coordinate system to another. When one coordinate system is just a rotation of the other, this...
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
Foreach
For each is a computer language idiom for traversing items in a collection. Foreach is usually used in place of a standard for statement. Unlike other for loop constructs, however, foreach loops usually maintain no explicit counter: they essentially say "do this to everything in this set",...
statement in C# can operate on any object providing such a method, even if it doesn't implement . Both interfaces were expanded into generic
Generic programming
In a broad definition, generic programming is a style of computer programming in which algorithms are written in terms of to-be-specified-later types that are then instantiated when needed for specific types provided as parameters...
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.0C Sharp 2.0The programming language C# introduces several new features in version 2.0 . These include:- Partial class :...
.
The .NET 2.0 Framework allowed C# to introduce an iterator
Iterator
In computer programming, an iterator is an object that enables a programmer to traverse a container. Various types of iterators are often provided via a container's interface...
that provides generator
Generator (computer science)
In computer science, a generator is a special routine that can be used to control the iteration behaviour of a loop. A generator is very similar to a function that returns an array, in that a generator has parameters, can be called, and generates a sequence of values...
functionality, 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.0C Sharp 3.0The programming language C# version 3.0 was released on 19 November 2007 as part of .NET Framework 3.5. It includes new features inspired by functional programming languages such as Haskell and ML, and is driven largely by the introduction of the Language Integrated Query pattern to the Common...
and .NET Framework 3.0.
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, which makes it easier to access to databases and their data.
Query syntax
The LINQ query syntax was introduced in C# 3.0 and lets you write SQLSQL
SQL is a programming language designed for managing data in relational database management systems ....
-like queries in C#.
The statements are compiled into method calls, whereby almost only the names of the methods are specified. Which methods are ultimately used is determined by normal overload resolution. Thus, the end result of the translation is affected by what symbols are in scope.
What differs from SQL is that the from-statement comes first and not last as in SQL. This is because it seems more natural writing like this in C# and supports Intellisense.
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 ways to create anonymous methods. Prior to C# 3.0 there was limited support by using delegates.
See also
- Anonymous functionAnonymous functionIn programming language theory, an anonymous function is a function defined, and possibly called, without being bound to an identifier. Anonymous functions are convenient to pass as an argument to a higher-order function and are ubiquitous in languages with first-class functions such as Haskell...
- Closure (computer science)Closure (computer science)In computer science, a closure is a function together with a referencing environment for the non-local variables of that function. A closure allows a function to access variables outside its typical scope. Such a function is said to be "closed over" its free variables...
Anonymous delegates
- This is a feature of C Sharp 2.0C Sharp 2.0The programming language C# introduces several new features in version 2.0 . These include:- Partial class :...
.
Anonymous delegates are functions pointers that are holding anonymous methods. The purpose is to make it simpler to use delegates by simplifying the process of assigning the function. Instead of declaring a separate method in code the programmer can use the syntax to write the code inline and the compiler will then generate an anonymous function for it.
Lambda expressions
- This is a feature of C Sharp 3.0C Sharp 3.0The programming language C# version 3.0 was released on 19 November 2007 as part of .NET Framework 3.5. It includes new features inspired by functional programming languages such as Haskell and ML, and is driven largely by the introduction of the Language Integrated Query pattern to the Common...
.
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.
Multi-statement lambdas have bodies enclosed by brackets and inside of them code can be written like in standard methods.
Lambda expressions can be passed as arguments directly in method calls similar to anonymous delegates but with a more aesthetic syntax.
Lambda expressions are essentially compiler-generated methods that are passed via delegates. These methods are reserved for the compiler only and can not be used in any other context.
Anonymous types
- This is a feature of C Sharp 3.0C Sharp 3.0The programming language C# version 3.0 was released on 19 November 2007 as part of .NET Framework 3.5. It includes new features inspired by functional programming languages such as Haskell and ML, and is driven largely by the introduction of the Language Integrated Query pattern to the Common...
.
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 an 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.0C Sharp 3.0The programming language C# version 3.0 was released on 19 November 2007 as part of .NET Framework 3.5. It includes new features inspired by functional programming languages such as Haskell and ML, and is driven largely by the introduction of the Language Integrated Query pattern to the Common...
.
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 were an instance method; the receiver of the call is bound to the first parameter of the method, decorated with keyword :
See also
- Decorator patternDecorator patternIn object-oriented programming, the decorator pattern is a design pattern that allows behaviour to be added to an existing object dynamically.-Introduction:...
Closure Blocks
C# implements closure blocks by means of the statement. The statement accepts an expression which results in an object implementing , and the compiler generates code that guarantees the object's disposal when the scope of the -statement is exited. The statement is syntactic sugarSyntactic sugar
Syntactic sugar is a computer science term that refers to syntax within a programming language that is designed to make things easier to read or to express....
, but it is much more readable than the equivalent pure C# code.
Thread synchronization
C# provides the statement, which is yet another example of beneficial syntactic sugar. It works by marking a block of code as a critical sectionCritical section
In concurrent programming a critical section is a piece of code that accesses a shared resource that must not be concurrently accessed by more than one thread of execution. A critical section will usually terminate in fixed time, and a thread, task or process will have to wait a fixed time to...
by mutual exclusion of access to a provided object. Like the statement, it works by the compiler generating a block in its place.
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. Attributes can be used for better maintenance of preprocessor directives.The .NET Framework comes with predefined attributes that can be used. Some of them serve an important role at runtime while some are just for syntactic decoration in code like . It does only mark that it is a compiler-generated element. Programmer-defined attributes can also be created.
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 preprocessorC preprocessor
The C preprocessor is the preprocessor for the C and C++ computer programming languages. The preprocessor handles directives for source file inclusion , macro definitions , and conditional inclusion ....
that allow programmers to define symbol
Symbol
A symbol is something which represents an idea, a physical entity or a process but is distinct from it. The purpose of a symbol is to communicate meaning. For example, a red octagon may be a symbol for "STOP". On a map, a picture of a tent might represent a campsite. Numerals are symbols for...
s, but not macros. Conditionals such as , , and are also provided.
Directives such as give hints to editors for code folding
Code folding
Code folding is a feature of some text editors, source code editors and IDEs that allows the user to selectively hide and display sections of a currently-edited file as a part of routine edit operations...
. The block must be terminated with a directive.
Code comments
C# utilizes a double forward slashSlash (punctuation)
The slash is a sign used as a punctuation mark and for various other purposes. It is now often called a forward slash , and many other alternative names.-History:...
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 JavadocJavadoc
Javadoc is a documentation generator from Sun Microsystems for generating API documentation in HTML format from Java source code.The "doc comments" format used by Javadoc is the de facto industry standard for documenting Java classes. Some IDEs, such as Netbeans and Eclipse automatically generate...
, but based on XML
Extensible Markup Language
Extensible Markup Language is a set of rules for encoding documents in machine-readable form. It is defined in the XML 1.0 Specification produced by the W3C, and several other related specifications, all gratis open standards....
. Two methods of documentation are currently supported by the C# compiler
Compiler
A compiler is a computer program that transforms source code written in a programming language into another computer language...
.
Single-line documentation comments, such as those commonly found in Visual Studio
Microsoft Visual Studio
Microsoft Visual Studio is an integrated development environment from Microsoft. It is used to develop console and graphical user interface applications along with Windows Forms applications, web sites, web applications, and web services in both native code together with managed code for all...
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
.NET Framework
The .NET Framework is a software framework that runs primarily on Microsoft Windows. It includes a large library and supports several programming languages which allows language interoperability...
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
XML
Extensible Markup Language is a set of rules for encoding documents in machine-readable form. It is defined in the XML 1.0 Specification produced by the W3C, and several other related specifications, all gratis open standards....
markup is defined in a non-normative annex of the ECMA
Ecma International
Ecma International is an international, private non-profit standards organization for information and communication systems. It acquired its name in 1994, when the European Computer Manufacturers Association changed its name to reflect the organization's global reach and activities...
C# standard. The same standard also defines rules for processing of such comments, and their transformation to a plain XML
XML
Extensible Markup Language is a set of rules for encoding documents in machine-readable form. It is defined in the XML 1.0 Specification produced by the W3C, and several other related specifications, all gratis open standards....
document with precise rules for mapping of Common Language Infrastructure
Common Language Infrastructure
The Common Language Infrastructure is an open specification developed by Microsoft and standardized by ISO and ECMA that describes the executable code and runtime environment that form the core of the Microsoft .NET Framework and the free and open source implementations Mono and Portable.NET...
(CLI) identifiers to their related documentation elements. This allows any C# integrated development environment
Integrated development environment
An integrated development environment is a software application that provides comprehensive facilities to computer programmers for software development...
(IDE) or other development tool to find documentation for any symbol in the code in a certain well-defined way.
Future features
This section presents features of the planned 5th version of the C# specification.Asynchronous programming syntax
C# will have native language support for asynchrony. As .NET Framework 4 there is a task library thatmakes it easier to write parallel and multi-threaded applications through tasks. This has made it easier writing concurrent code but it has yet been proven a bit hard from the perspective of the ordinary programmer.
The next version of C# will introduce a new syntax that makes it easier writing asynchronous. Introducing asynchronous methods and the keyword.
Spec#
Spec# is a dialect of C# that is developed in parallel with the standard implementation from Microsoft. It extends C# with specification language features and is a possible future feature to the C# language. It also adds syntax for the code contracts API that was introduced in .NET Framework 4.0. Spec# is being developed by Microsoft ResearchMicrosoft Research
Microsoft Research is the research division of Microsoft created in 1991 for developing various computer science ideas and integrating them into Microsoft products. It currently employs Turing Award winners C.A.R. Hoare, Butler Lampson, and Charles P...
.
This sample shows two of the basic structures that are used when adding contracts to your code.
is used to make a reference type non-nullable, e.g. you cannot set the value to . This in contrast of nullable types which allow value types to be set as .
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.
Non-nullable types
Spec# extends C# with non-nullable types that simply checks so the variables of nullable types that has been set as non-nullable are not . If is then an exception will be thrown.In use:
Preconditions
Preconditions are checked before a method is executed.Postconditions
Postconditions are conditions that are ensured to be correct when a method has been executed.Checked exceptions
Spec# adds checked exceptions like those in Java.See also
- .NET Framework.NET FrameworkThe .NET Framework is a software framework that runs primarily on Microsoft Windows. It includes a large library and supports several programming languages which allows language interoperability...
- C Sharp (programming language)
- Mono (software)Mono (software)Mono, pronounced , is a free and open source project led by Xamarin to create an Ecma standard compliant .NET-compatible set of tools including, among others, a C# compiler and a Common Language Runtime....
- Visual C Sharp