In Depth
See Also

C Sharp

C# is an object-oriented programming language Programming language

A programming language is an artificial language [i] that can be used to control [i] ... 

 developed by Microsoft Microsoft

company_name = Microsoft Corporation ... 

 as part of their .NET initiative, and later approved as a standard by ECMA and ISO International Organization for Standardization

The International Organization for Standardization is an international standard-setting body composed o... 

. C# has a procedural, object-oriented syntax based on C++ C++

C++ is a general-purpose, high-level [i] programming language [i] with low-level [i] facilities. ... 

 that includes aspects of several other programming languages with a particular emphasis on simplification . This article describes the language as defined in the ECMA and ISO standards, and avoids description of Microsoft's implementation.

Discussions

  Discussion Features

   Ask a question about 'C Sharp'

   Start a new discussion about 'C Sharp'

   Answer questions about 'C Sharp'

   'C Sharp' discussion forum


Encyclopedia



C# is an object-oriented programming language Programming language

A programming language is an artificial language [i] that can be used to control [i] ... 

 developed by Microsoft Microsoft

company_name = Microsoft Corporation
... 

 as part of their .NET initiative, and later approved as a standard by ECMA and ISO International Organization for Standardization

The International Organization for Standardization is an international standard-setting body composed o... 

. C# has a procedural, object-oriented syntax based on C++ C++

C++ is a general-purpose, high-level [i] programming language [i] with low-level [i] facilities. ... 

 that includes aspects of several other programming languages with a particular emphasis on simplification .

This article describes the language as defined in the ECMA and ISO standards, and avoids description of Microsoft's implementation. For a description of Microsoft's implementation, see Microsoft Visual C#.

Language design goals

The ECMA standard lists these design goals for C#:

  • C# is intended to be a simple, modern, general-purpose, object-oriented programming language.
  • The language, and implementations thereof, should provide support for software engineering principles such as strong type checking, array bounds checking, detection of attempts to use uninitialized variables, and automatic garbage collection. Software robustness, durability, and programmer productivity are important.
  • The language is intended for use in developing software components suitable for deployment in distributed environments.
  • Source code portability is very important, as is programmer portability, especially for those programmers already familiar with C and C++.
  • Support for internationalization is very important.
  • C# is intended to be suitable for writing applications for both hosted and embedded systems, ranging from the very large that use sophisticated operating systems, down to the very small having dedicated functions.
  • Although C# applications are intended to be economical with regards to memory and processing power requirements, the language was not intended to compete directly on performance and size with C or assembly language.

Architectural history

C#'s principal designer, and lead architect at Microsoft, is Anders Hejlsberg Anders Hejlsberg

Anders Hejlsberg is an influential Danish [i] software engineer [i] who co-designed several pop ... 

. His previous experience in programming language and framework design can be readily seen in the syntax of the C# language, as well as throughout the CLR core. He can be cited in interviews and technical papers as stating flaws in most major programming languages, for example, C++ C++

C++ is a general-purpose, high-level [i] programming language [i] with low-level [i] facilities. ... 

, Java Java (programming language)

Java is an object-oriented [i] programming language [i] developed by James Gosling [i] ... 

, Delphi Object Pascal

Object Pascal is an object oriented [i] derivative of Pascal [i] ... 

, Smalltalk, were what drove the fundamentals of the CLR, which, in turn, drove the design of the C# programming language itself. His expertise can be seen in C#. Some argue that C# shares roots in other languages, as purported by

Language features

C# is, in some senses, the programming language which most directly reflects the underlying Common Language Infrastructure Common Language Infrastructure

The Common Language Infrastructure is an open specification [i] developed by Microsoft [i] that describ ... 

 . It was designed specifically to take advantage of the features that the CLI provides. 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, or generate Microsoft Intermediate Language Microsoft Intermediate Language

The word Maori refers to the indigenous people [i] of New Zealand [i] and to their language [i] ... 

 , or generate any other specific format. Theoretically, a C# compiler could generate machine code like traditional compilers of C++ or FORTRAN. That said, the Microsoft implementation of C# is by far the predominant one, and this article describes its characteristics and behavior, unless noted otherwise.

Compared to C and C++, the language is restricted or enhanced in a number of ways, including but not limited to the following:

  • There are no global variables. All methods and members must be declared as part of a class.
  • Variable names cannot be duplicated in enclosing blocks, unlike C and C++. This is often treated as a potential cause of confusion and ambiguity in C++ texts, but C# simply disallows this case.
  • Instead of functions being visible globally, such as the printf function in C, all functions must be declared in classes. Classes are almost always organized into namespaces in order to prevent naming conflicts.
  • Namespaces are hierarchical. Namespaces may also be declared in other namespaces.
  • All types, including primitives such as integers, are subclasses of the object class, and so all inherit the properties and methods of object. For example, every type has a ToString method.
  • C# supports a boolean type, bool. Statements that take conditions, such as while and if, require an expression of a boolean type. While C and C++ do have a boolean type, it can be freely converted to and from integers, and expressions such as if 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 helps prevent certain types of programming mistakes.
  • True support for pointers. Pointers can only be used within unsafe scopes, and only programs with appropriate permissions can execute code marked as unsafe. Most object access is done through safe references, which cannot be made invalid, and most arithmetic is checked for overflow. An unsafe pointer can be made to value-types and strings. Safe code can store and manipulate pointers through the System.IntPtr type.
  • Managed memory cannot be explicitly freed, but instead is automatically garbage collected when no references to the memory exist. Garbage collection addresses a common programming mistake of allocating memory and not releasing it, known as a memory leak. C# also provides explicit control of unmanaged resources, such as database connections, through the IDisposable interface and the using statement, which together are an explicit form of "Resource Acquisition Is Initialization" .
  • Multiple inheritance is not supported, although a class can implement any number of interfaces. This was a design decision by the language's lead architect to avoid complication, avoid "dependency hell," and simplify architectural requirements throughout CLI.
  • C# is more typesafe than C++. The only implicit conversions by default are safe conversions, such as widening of integers and conversion from a derived type to a base type. This is enforced at compile-time, during JIT, and, in some dynamic cases, at runtime. There are no implicit conversions between booleans and integers and between enumeration members and integers, and any user-defined implicit conversion must be explicitly marked as such, unlike C++'s copy constructors.
  • Enumeration members are placed in their own namespace.
  • Accessors called properties can be used to modify an object with syntax that resembles C++ member field access. In C++, declaring a member public enables both reading and writing to that member. In C#, properties allow control over member access and data validation.
  • Full type reflection and discovery is available.

C# 2.0 new language features

New features in C# for the .NET SDK 2.0 are:
  • Partial classes allow class implementation across more than one file. This permits breaking down very large classes, or is useful if some parts of a class are machine-generated. Unlike VB, the partial keyword must appear in declaration of all classes.


file1:

public partial class MyClass1


file2:

public partial class MyClass1


  • Generics or parameterized types. This is a .NET 2.0 feature supported by C#. Unlike C++ templates .NET parameterized types are specialized 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, although in C++ these can be easily implemented. On the other hand, expressions cannot be used as generic parameters, as with C++ templates. Also, they differ from Java in that parameterized types are first-class objects in the Virtual Machine, which allows for optimizations and preservation of the type information. Generics were initially designed and implemented by Microsoft Research, Cambridge. A template language feature for value types also exists.
  • Static classes which represent a concept close to VB.NET modules, cannot be instantiated from code and allow only static members.
  • A new form of iterator that employs coroutines via a functional-style yield keyword similar to yield in Python Python (programming language)

    Python is a programming language [i] created by Guido van Rossum [i] in 1990 [i]. ... 

    .
  • Anonymous delegates providing closure functionality.
  • Covariance and contravariance Covariance and contravariance

    In mathematics [i] and theoretical physics [i], covariance and contravariance are concepts used in ... 

     for signatures of delegates
  • The accessibility of property get and set accessors can be set independently. Example:


string status = string.Empty;
public string Status


  • Nullable value types , allowing improved interaction with SQL databases.


Nullable types received an eleventh hour improvement at the end of August 2005 , to improve their boxing Boxing

Boxing, also called Western Boxing, prizefighting or the sweet science , is a sport [i] ... 

 characteristics: a nullable variable which is assigned null is not actually a null reference . Hence boxing this value would result in a non-null reference. The following code illustrates the flaw:

int? i = null;
object o = i;
if
Console.WriteLine;
else
Console.WriteLine;

The late nature of this fix caused some controversy, since it required core-CLR changes affecting not only .NET2, but all dependent technologies .
  • Coalesce operator: returns the first of its operands which is not null:


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:

int? i = null;
int j = i ?? default; //can't assign null to int

C# 3.0 new language features

In C# 3.0 there will be new features, driven largely by the introduction of the Language Integrated Query  pattern:
  • "from, where, select" keywords allowing to query from SQL, XML, collections, and more
  • Object initialization : Customer c = new Customer; c.Name = "James"; can be written Customer c = new Customer ;
  • Lambda expressions: listOfFoo.Where can be written listOfFoo.Where;
  • Compiler-inferred translation of Lambda expressions to either strongly-typed function delegates or strongly-typed expression trees
  • Anonymous types: var x = new
  • Local variable type inference: var x = "hello"; is interchangeable with string x = "hello";. Aside from allowing this syntactic sugar -- which can be of great use when dealing with complex generic types -- it's required to allow the declaration of anonymously-typed variables because the true name of the type is known only to the compiler at compile time.
  • Extension methods :

public static class IntExtensions

int foo = 0;
foo.PrintPlusOne;

C# 3.0 was unveiled at the PDC 2005. A preview with specifications is available from the .

Microsoft has emphasized that the new language features of C# 3.0 will be available without any changes to the .NET runtime. As a result, C# 2.0 and 3.0 will both be bytecode-compatible with the .NET framework 2.0.

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.

See also Language Integrated Query.

Code libraries

The ECMA C# specification details a minimum set of types and class libraries that the compiler expects to have available and they define the basics required. Most implementations in the open ship with the larger set of libraries.

The .NET Framework .NET Framework

The Microsoft .NET Framework is a software component [i] which can be added to the ... 

 is a class library which can be used from a .NET language to perform tasks from simple data representation and string manipulation to generating dynamic web page Dynamic web page

On the classical hypertext [i], navigation is performed through "static" documents [i]. ... 

s , XML parsing, Web Services Web service

}

The W3C [i] defines a Web service as a software system designed to support interoperable [i]... 

/Remoting and reflection. The code is organized into a set of namespaces which group together classes with a similar function, e.g. System.Drawing for graphics, System.Collections for data structure Data structure

In computer science [i], a data structure is a way of storing data [i] in a computer so that it can be u ... 

s and System.Windows.Forms for the Windows Forms Windows Forms

Windows Forms is the name given to the graphical user interface [i] application programming interface [i] ... 

 system.

A further level of organisation is provided by the concept of an assembly. An assembly can be a single file or multiple files linked together which may contain many namespaces and objects. Programs needing classes to perform a particular function might reference assemblies such as System.Drawing.dll and System.Windows.Forms.dll as well as the core library .

Hello world example

The following is a very simple C# program, a version of the classic "Hello world" example.

public class ExampleClass


The effect is to write the text Hello, world! to the output console. Each line serves a specific purpose, as follows:

public class ExampleClass

This is a class definition. It is public, meaning objects in other projects can freely use this class. All the information between the following braces describes this class.

public static void Main

This is the entry point where the program begins execution. It could be called from other code using the syntax ExampleClass.Main.

System.Console.WriteLine;

This line performs the actual task of writing the output. Console is a system object, representing a command-line console where a program can input and output text. The program calls the Console method WriteLine, which causes the string passed to it to be displayed on the console.

Standardization

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 to the international standardization organization ECMA.
In December 2001, ECMA released ECMA-334 C# Language Specification. C# became an ISO standard in 2003 . 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 .
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.

ECMA specification 334 covers only the C# language. Programs written in C# commonly use the .NET framework .NET Framework

The Microsoft .NET Framework is a software component [i] which can be added to the ... 

, which is partly described by other specifications and is partly proprietary to Microsoft.

Microsoft released support of the 3rd edition of C# in the .NET SDK 2.0, and Visual Studio 2005, in November 2005.

Microsoft has made it clear that C#, as well as the other .NET languages, is an important part of its software strategy for both internal use and external consumption. The company takes an active role in marketing the language as part of its overall business strategies.

Implementations

There are four known C# compilers:
  • The de facto standard implementation of the C# language is Microsoft's Visual C#.
  • Microsoft's Rotor project provides a shared source implementation of the CLR runtime and a C# compiler.
  • The Mono project provides a CLR runtime, an implementation of the .NET libraries, and a C# compiler.
  • The Dot GNU DotGNU

    DotGNU is a part of the GNU [i] initiative that aims to provide a free software [i] replacement for the ... 

     project provides a CLR runtime, an implementation of the .NET libraries, and a C# compiler.

Language name

According to the ECMA-334 C# Language Specification, section 6, Acronyms and abbreviations the name of the language is written "C#" and pronounced "C Sharp".


Due to technical limitations of display and the fact that the sharp symbol 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 . Although Microsoft's refers to the sharp symbol in the language name, Microsoft clarifies the language name as follows:

The spoken name of the language is "C sharp" in reference to the musical "sharp" sign, which increases a tone denoted by a letter by half a tone. However, for ease of typing it was decided to represent the sharp sign by a pound symbol rather than the "musically correct" Unicode sharp sign. The Microsoft and ECMA 334 representation symbols thus agree: the # in C# is the pound sign, but it represents a sharp sign. Think of it in the same way as the <= glyph in C languages which is a less than sign and an equals sign, but represents a less-than-or-equals sign., Microsoft Online Customer Service


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 , some incorrectly uses the sharp symbol.

The "sharp" suffix has been used by a number of other .NET languages that are variants of existing languages, including J# , A# , and F# . The suffix is also sometimes used for libraries, such as Gtk# Gtk Sharp

Gtk# is a set of .NET [i] bindings [i] for the GTK+ [i] GUI [i] ... 

  and Cocoa# .

One interpretation of the name C# is that it denotes an improved version of C, by analogy with the musical note, which is half a step above the C note. This is similar to the play on words used by the language name C++; "++" is a C operator that increases a variable by one.

Another interpretation is that the sharp symbol represents 4 plus symbols together, C++ with another ++ on top.

See also

  • Comparison of C# and Java
  • Comparison of C# and Visual Basic.Net
  • Common Language Runtime
  • SharpDevelop SharpDevelop

    SharpDevelop is a free and open source [i] IDE [i] for the C# [i] ... 

    , an open-source C# IDE for Windows Microsoft Windows

    Microsoft Windows is a family of operating system [i]s by Microsoft [i].... 

  • Mono, an open source implementation of .NET
  • MonoDevelop MonoDevelop

    MonoDevelop is a free [i] GNOME [i] IDE [i] primarily d ... 

    , an open-source C# IDE for Linux Linux

    Linux is a Unix-like [i] computer operating system [i]. ... 

  • C? programming language, extension to C#
  • Spec#
  • Sing#
  • Nemerle programming language Nemerle

    Nemerle is a high-level [i] statically-typed [i] programming language [i] ... 

  • Boo programming language, a cross between C# and Python Python (programming language)

    Python is a programming language [i] created by Guido van Rossum [i] in 1990 [i]. ... 

  • IronPython, a Microsoft Microsoft

    company_name = Microsoft Corporation

... 

-supported, .NET-compliant version of Python Python (programming language)

Python is a programming language [i] created by Guido van Rossum [i] in 1990 [i]. ... 


  • Polyphonic C#
  • Anders Hejlsberg Anders Hejlsberg

    Anders Hejlsberg is an influential Danish [i] software engineer [i] who co-designed several pop ... 

  • C++/CLI
  • Comparison of programming languages
  • Windows PowerShell Windows PowerShell

    Windows PowerShell, previously Microsoft Shell or MSH is a command line interface [i] shell ... 

    , a .NET-based interactive command line shell/scripting environment
  • Active record pattern, a pattern and some examples related to C# 3.0 features

External links

  • Anders Hejlsberg Anders Hejlsberg

    Anders Hejlsberg is an influential Danish [i] software engineer [i] who co-designed several pop ... 

    , C#'s creator, discusses the difference between the implementations of generics in C#, Java, and C++ in .

References