
The correct name of the programming language is C#. The substitution or omission of a # sign is because of technical restrictions.
C# (see section on name, pronunciation) is an object-oriented programming language developed by Microsoft as part of the .NET initiative and later approved as a standard by ECMA (ECMA-334) and ISO (ISO/IEC 23270). Anders Hejlsberg leads development of the C# language, which has a procedural, object-oriented syntax based on C++ and includes influences from aspects of several other programming languages (most notably Delphi and Java) with a particular emphasis on simplification.
The ECMA standard lists these design goals for C#:
During the development of .Net, the class libraries were originally written in a language/compiler called Simple Managed C (SMC)[1]
[2]. In January 1999, Anders Hejlsberg formed a team[3] to build a new language at the time called Cool. By the time the .Net project was publically announced at the July 2000 Professional Developers Conference (PDC), the language had been renamed C# and the class libraries and ASP.NET runtime had been ported to C#.
C#'s principal designer and lead architect at Microsoft is Anders Hejlsberg. His previous experience in programming language and framework design (Visual J++, Borland Delphi, Turbo Pascal) can be readily seen in the syntax of the C# language, as well as throughout the Common Language Runtime (CLR) core. In interviews and technical papers he has stated that flaws in most major programming languages (e.g. C++, Java, Delphi, and Smalltalk) drove the fundamentals of the CLR, which, in turn, drove the design of the C# programming language itself. Some argue that C# shares roots in other languages.[4]
The following description is based on the language standard and other documents listed in the External links section.
By design, C# is the programming language that most directly reflects the underlying Common Language Infrastructure (CLI). Most of C#'s intrinsic types correspond to value-types implemented by the CLI framework. However, the C# language specification does not state the code generation requirements of the compiler: that is, it does not state that a C# compiler must target a Common Language Runtime (CLR), or generate Common Intermediate Language (CIL), or generate any other specific format. Theoretically, a C# compiler could generate machine code like traditional compilers of C++ or FORTRAN; in practice, all existing C# implementations target CLI.
C# differs from C and C++ in many ways, including:
bool. Statements that take conditions, such as while and if, require an expression of a boolean type. While C++ also has a boolean type, it can be freely converted to and from integers, and expressions such as if(a) require only that a is convertible to bool, allowing a to be an int, or a pointer. C# disallows this "integer meaning true or false" approach on the grounds that forcing programmers to use expressions that return exactly bool can prevent certain types of programming mistakes such as if (a = b) (use of = instead of ==).System.IntPtr type, but cannot dereference them.using statement (supporting the Resource Acquisition Is Initialization idiom).C# has a unified type system. This unified type system is called Common Type System(CTS).
A unified type system implies that all types, including primitives such as integers, are subclasses of the System.Object class. For example, every type inherits a ToString() method. For performance reasons, primitive types (and value types in general) are internally allocated on the stack.
CTS separates datatypes into two categories:
While value types are those in which the value itself is stored by allocating memory on the stack, reference types are those in which only the address to the location where the value is present, is stored. Value types include integers (short, long, float, double), structures, enumerators, booleans and characters while reference types include objects, strings, classes, interfaces and delegates.
C# also allows the programmer to create user-defined value types, using the struct keyword. From the programmer's perspective, they can be seen as lightweight classes. Unlike regular classes, and like the standard primitives, such value types are allocated on the stack rather than on the heap. They can also be part of an object (either as a field or boxed), or stored in an array, without the memory indirection that normally exists for class types. Structs also come with a number of limitations. Because structs have no notion of a null value and can be used in arrays without initialization, they are implicitly initialized to default values (normally by filling the struct memory space with zeroes, but the programmer can specify explicit default values to override this). The programmer can define additional constructors with one or more arguments. This also means that structs lack a virtual method table, and because of that (and the fixed memory footprint), they cannot allow inheritance (but can implement interfaces).
Type casting is the process of converting a value belonging to a particular data type (or instance) to another.
Example:
csharp
using System;
class Employee { }
class ContractEmployee : Employee { }
class CastExample5
{
public static void Main ()
{
Employee e = new Employee();
Console.WriteLine("e = {0}",
e == null ? "null" : e.ToString());
ContractEmployee c = e as ContractEmployee;
Console.WriteLine("c = {0}",
c == null ? "null" : c.ToString());
}
}
Here, the element e, which is an instance of the class Employee, is type cast as an instance of the class ContractEmployee and stored in element c.
Certain datatypes are incompatible for type casting. For example, an integer value cannot be type-casted into a string though the converse is possible. With regard to user-defined data types, the compiler allows all kinds of type-casting. However, a TypeCastException is thrown at runtime if the datatypes are incompatible.
Boxing and unboxing are two new concepts introduced in C#.
Boxing is the method used to convert a value type into a reference type.
Example:
csharp
int foo = 42; // Value type. object bar = foo; // foo is boxed to bar.
Unboxing is the method used to convert a reference type into a data type.
Example:
csharp
int foo = 42; // Value type. object bar = foo; // foo is boxed to bar. int foo2 = (int)bar; // Unboxed back to int.
New features in C# for the .NET SDK 2.0 (corresponding to the 3rd edition of the ECMA-334 standard) are:
file1.cs:
csharp
public partial class MyClass
{
public MyClass()
{
// implementation
}
}
file2.cs:
csharp
public partial class MyClass
{
public void SomeMethod()
{
// implementation
}
}
yield return construct similar to yield in Python.csharp
// Method that takes an iterable input (possibly an array) and returns all even numbers.
public static IEnumerable<int> GetEven(IEnumerable<int> numbers)
{
foreach (int i in numbers)
{
if (i % 2 == 0) yield return i;
}
}
csharp
public void Foo(object parameter) {
// ...
ThreadPool.QueueUserWorkItem(delegate
{
// anonymous delegates have full access to local variables of the enclosing method
if (parameter == ...)
{
// ...
}
// ...
});
}
csharp
string status = string.Empty;
public string Status
{
get { return status; } // anyone can get value of this property,
protected set { status = value; } // but only derived classes can change it
}
int? i = null;) which add null to the set of allowed values for any value type. This provides improved interaction with SQL databases, which can have nullable columns of types corresponding to C# primitive types: an SQL INTEGER NULL column type directly translates to the C# int?.Nullable types received an eleventh-hour improvement at the end of August 2005, mere weeks before the official launch, to improve their boxing characteristics: a nullable variable which is assigned null is not actually a null reference, but rather an instance of struct Nullable<T> with property HasValue equal to false. When boxed, the Nullable instance itself is boxed, and not the value stored in it, so the resulting reference would always be non-null, even for null values. The following code illustrates the corrected flaw:
csharp
int? i = null;
object o = i;
if (o == null)
Console.WriteLine("Correct behaviour - runtime version from September 2005 or later");
else
Console.WriteLine("Incorrect behaviour - pre-release runtime (from before September 2005)");
When copied into objects, the official release boxes values from Nullable instances, so null values and null references are considered equal. The late nature of this fix caused some controversy, since it required core-CLR changes affecting not only .NET2, but all dependent technologies (including C#, VB, SQL Server 2005 and Visual Studio 2005).
??) returns the first of its operands which is not null (or null, if no such operand exists): csharp
object nullObj = null; object obj = new Object(); return nullObj ?? obj; // returns obj
The primary use of this operator is to assign a nullable type to a non-nullable type with an easy syntax:
csharp
int? i = null; int j = i ?? 0; // Unless i is null, initialize j to i. Else (if i is null), initialize j to 0.
C# 3.0 is the current version, and 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 (LINQ) pattern to the Common Language Runtime.[5]
from, where, select" context-sensitive keywords allowing queries across SQL, XML, collections, and more. These are treated as keywords in the LINQ context, but their addition won't break existing variables named from, where, or select.Customer c = new Customer(); c.Name = "James"; can be written Customer c = new Customer { Name="James" };MyList list = new MyList(); list.Add(1); list.Add(2); can be written as MyList list = new MyList { 1, 2 }; (assuming that MyList implements System.Collections.IEnumerable and has a public Add method[7])var x = new { Name = "James" }var x = "hello"; is interchangeable with string x = "hello";. More than just syntactic sugar, this feature is required for the declaration of anonymous typed variables.int[] arr = new int[] { 1, 2, 3 } can now be written as var arr = new[] { 1, 2, 3 }.listOfFoo.Where(delegate(Foo x) { return x.size > 10; }) can be written listOfFoo.Where(x => x.size > 10);public string Name { get; private set; }this keyword in the first parameter of a method on another static class):csharp
public static class IntExtensions
{
public static void PrintPlusOne(this int x) { Console.WriteLine(x + 1); }
}
int foo = 0;
foo.PrintPlusOne();
C# 3.0 was unveiled at the 2005 Professional Developers Conference.[9] It is not currently standardized by any standards organisation, though it is expected that it will eventually become an ECMA and then ISO standard, as did its predecessors.
Microsoft has emphasized that the new language features of C# 3.0 will be available without any changes to the runtime. This means that C# 2.0 and 3.0 will be binary-compatible (CLI implementations compatible with 2.0 are able to run 3.0 applications directly).
Although the new features may only slightly change simple in-memory queries, such as List.FindAll or List.RemoveAll, the pattern used by LINQ allows for significant extension points to enable queries over different forms of data, both local and remote.
C# features "preprocessor directives"[10] (though it does not have an actual preprocessor) based on the C preprocessor that allow programmers to define symbols but not macros. Conditionals such as #if, #endif, and #else are also provided. Directives such as #region give hints to editors for code folding.
C# utilizes a double forward slash (//<code>) to indicate the rest of the line is a comment. Comments can also be indicated using a starting forward slash/asterisk (<code>/*<code>) and ending asterisk/forward slash (<code>*/<code>).
<source lang="csharp">
public class Foo
{
// a comment
public static void Bar(int firstParam) {} //Also a comment
}
public class FooBar
{
/* a comment */
public static void BarFoo(int firstParam) {} /* Also a comment */
}
</source>
Multi-line comments can also be indicated by a starting forward slash/asterisk (<code>/*<code>) and ending asterisk/forward slash (<code>*/<code>).
<source lang="csharp">
public class Foo
{
/* A Multi-Line
comment */
public static void Bar(int firstParam) {}
}
</source>
== XML documentation system ==
C#'s documentation system is similar to Java's [[Javadoc]], but based on [[Extensible Markup Language|XML]]. Two methods of documentation are currently supported by the C# [[compiler]].
Single-line comments, such as those commonly found in [[Microsoft Visual Studio|Visual Studio]] generated code, are indicated on a line beginning with <code>///<code>.
<source lang="csharp">
public class Foo
{
/// <summary>A summary of the method.</summary>
/// <param name="firstParam">A description of the parameter.</param>
/// <remarks>Remarks about the method.</remarks>
public static void Bar(int firstParam) {}
}
</source>
Multi-line comments, while defined in the version 1.0 language specification, were not supported until the [[.NET Framework|.NET]] 1.1 release.<ref>{{cite web | url=http://blogs.msdn.com/ansonh/archive/2006/09/11/750056.aspx | title=C# XML documentation comments FAQ | accessdate=2007-12-11 | author=Anson Horton |date=2007-09-11 }}</ref> These comments are designated by a starting forward slash/asterisk/asterisk (<code>/**<code>) and ending asterisk/forward slash (<code>*/<code>)<ref name="Delimiters for Documentation Tags">http://msdn2.microsoft.com/en-us/library/5fz4y783(VS.71).aspx Delimiters for Documentation Tags</ref>.
<source lang="csharp">
public class Foo
{
/** <summary>A summary of the method.</summary>
* <param name="firstParam">A description of the parameter.</param>
* <remarks>Remarks about the method.</remarks> */
public static void Bar(int firstParam) {}
}
</source>
Note there is some stringent criteria regarding white space and XML documentation when using the forward slash/asterisk/asterisk (<code>/**<code>) technique.
This code block:
<source lang="csharp">
/**
* <summary>
* A summary of the method.</summary>*/
</source>
produces a different XML comment than this code block<ref name="Delimiters for Documentation Tags">http://msdn2.microsoft.com/en-us/library/5fz4y783(VS.71).aspx Delimiters for Documentation Tags</ref>:
<source lang="csharp">
/**
* <summary>
A summary of the method.</summary>*/
</source>
Syntax for documentation comments and their [[XML]] markup is defined in a non-normative annex of the [[Ecma International|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 [[Common Language Infrastructure|CLI]] identifiers to their related documentation elements. This allows any C# [[Integrated development environment|IDE]] or other development tool to find documentation for any symbol in the code in a certain well-defined way.
== Future development ==
{{future software}}
Future versions of C# are under development, though their exact specification is not finalized. It will feature enhanced support for [[Reflection (computer science)|Reflection]] as well as an enhanced [[Microsoft Office]] [[Visual Studio Tools for Office|interop library]]. It will also integrate will the [[Dynamic Language Runtime]] and allow C# to call into code written in DLR-based languages (such as [[IronPython]] and [[IronRuby]] using a syntax similar to what C# uses for CLR methods and objects. The <code>dynamic keyword is being considered to demarcate a block where dynamic lookup will be available.[11]
The C# specification details a minimum set of types and class libraries that the compiler expects to have available and they define the basics required. In practice, C# is most often used with some implementation of the Common Language Infrastructure (CLI), which is standardized as ECMA-335 Common Language Infrastructure (CLI).
The following is a very simple C# program, a version of the classic "Hello world" example:
csharp
class ExampleClass
{
static void Main()
{
System.Console.WriteLine("Hello, world!");
}
}
The effect is to write the following text to the output console:
Hello, world!
Each line has a purpose:
csharp
class ExampleClass
Above is a class definition. Everything between the following pair of braces describes ExampleClass.
csharp
static void Main()
This declares the class member method where the program begins execution. The .NET runtime calls the Main method. (Note: Main may also be called from elsewhere, e.g. from the code Main() in another method of ExampleClass.) The static keyword makes the method accessible without an instance of ExampleClass. Each console application's Main entry point must be declared static. Otherwise, the program would require an instance, but any instance would require a program. To avoid that irresolvable circular dependency, C# compilers processing console applications (like above) report an error if there is no static Main method. The void keyword declares that Main has no return value. (See also, Side effect (computer science).)
csharp
System.Console.WriteLine("Hello, world!");
This line writes the output. Console is a static class in the System namespace. It provides an interface to the standard input, output, and error streams for console applications. The program calls the Console method WriteLine, which displays on the console a line with the argument, the string "Hello, world!".
In August, 2000, Microsoft Corporation, Hewlett-Packard and Intel Corporation co-sponsored the submission of specifications for C# as well as the Common Language Infrastructure (CLI) to the international standardization organization ECMA.
In December 2001 , ECMA released ECMA-334 C# Language Specification. C# became an ISO standard in 2003 (ISO/IEC 23270:2006 - Information technology -- Programming languages -- C#). ECMA had previously adopted equivalent specifications as the 2nd edition of C#, in December, 2002.
In June 2005, ECMA approved edition 3 of the C# specification, and updated ECMA-334. Additions included partial classes, anonymous methods, nullable types, and generics (similar to C++ templates).
In July 2005, ECMA submitted the standards and related TRs to ISO/IEC JTC 1 via the latter's Fast-Track process. This process usually takes 6-9 months.
;Performance : C# programs, like all programs written for the .NET and other virtual machine environments such as Java, tend to require more system resources than functionally similar applications that access machine resources more directly.[12][13]
;Platform : Microsoft's current .NET implementation is only available on Windows, and while this only relates to the availability of some non-standard libraries developed by Microsoft, rather than the C# language itself, the .NET runtime's ties to this operating system are seen by some as a drawback.[14][15]. However, there are other environments that support C# programs on Windows, Linux, BSD or Mac OS X, and while some provide a complete implementation of the C# language and CLI, none provide a complete implementation of every library available from Microsoft. See Mono[16] and DotGNU[17] In November of 2002 Microsoft released a 1.0 CLI implementation that worked on Free BSD and Mac OS X 10.2, but the next versions were only made available on Windows.
;Licensing : Although the C# language definition and the CLI are standardized under ISO and ECMA standards, the CLI is only a part of Microsoft's Base Class Library, which also contains non-standardized classes that are used by many C# programs (some extended IO, User Interface, Web services, ...). Furthermore, parts of the BCL have been patented by Microsoft,[18][19] which may deter independent implementations of the full framework, as only the standardized portions have RAND protection from patent claims.
The de facto standard implementation of the C# language is Microsoft's C# compiler, Visual C#.
Alternative C# compilers are:
According to the ECMA-334 C# Language Specification, section 6, Acronyms and abbreviations[20] the name of the language is written "C#" ("LATIN CAPITAL LETTER C (U+0043) followed by the NUMBER SIGN # (U+0023)") and pronounced "C Sharp".
Due to technical limitations of display (fonts, browsers, etc.) and the fact that the sharp symbol (, U+266F, MUSIC SHARP SIGN, see graphic at right if the symbol is not visible) is not present on the standard keyboard, the number sign (#) was chosen to represent the sharp symbol in the written name of the language. So, although the symbol in "C#" represents the sharp symbol, it is actually the number sign ("#"). Microsoft's C# FAQ refers to the sharp symbol in the language name.[21] James Kovacs, a Microsoft MVP, explains some of the history of C#.[22]
The choice to represent the sharp symbol () with the number sign (#) has led to confusion regarding the name of the language. For example, although most printed literature uses the correct number sign,[23] some (including from Microsoft's own material) incorrectly use the sharp symbol.[24]
The "sharp" suffix has been used by a number of other .NET languages that are variants of existing languages, including J# (Microsoft's implementation of Java), A# (from Ada), and F# (presumably from System F, the type system used by the ML family)[25]. The original implementation of Eiffel for .NET was called Eiffel#, a name since retired since the full Eiffel language is now supported. The suffix is also sometimes used for libraries, such as Gtk# (a .NET wrapper for GTK+ and other GNOME libraries), Cocoa# (a wrapper for Cocoa) and Qt# (a .NET language binding for the Qt toolkit).