C Sharp (programming language): Difference between revisions

Content deleted Content added
rv changes by 137.111.13.34. Browser warning applies in this case.
rm "you" language, rm same-section duplicate links (MOS:DUPLINK), image caption style (MOS:CAPFRAG)
 
Line 1:
{{Short description|Programming language}}{{Correct title|title=C#|reason=#}}
{{wrongtitle|title=C♯}} ''(This may not be visible in all browsers, such as Opera)''
<!-- Per Ecma, "C#" (i.e. not "C♯") is the standard spelling of the name of the language. See "Name" section and talk page. -->
 
{{Use mdy dates|date= April 2020}}
: ''This article is about the C# programming language. For information about the musical note C#, see [[musical notation]].''
{{Infobox programming language
| name = C#
| logo = C_Sharp_Logo_2023.svg
| logo size = 165px
| paradigm = [[Multi-paradigm programming language|Multi-paradigm]]: [[Structured programming|structured]], [[Imperative programming|imperative]], [[Object-oriented programming|object-oriented]], [[Event-driven programming|event-driven]], [[The Task-based Asynchronous Pattern|task-driven]], [[Functional programming|functional]], [[Generic programming|generic]], [[Reflective programming|reflective]], [[Concurrent computing|concurrent]]
| family = [[List of C-family programming languages|C]]
| year = {{start date and age|2000}}<ref>{{Cite web | url=https://www.infoq.com/minibooks/emag-c-sharp-preview | title=InfoQ eMag: A Preview of C# 7 | access-date=November 11, 2016 | archive-date=April 24, 2023 | archive-url=https://web.archive.org/web/20230424033239/https://www.infoq.com/minibooks/emag-c-sharp-preview/ | url-status=live }}</ref>
| designer = [[Anders Hejlsberg]] ([[Microsoft]])
| developer = Mads Torgersen ([[Microsoft]])
| latest release version = {{wikidata|property|edit|reference|P548=Q2804309|P348}}
| latest release date = {{start date and age|{{wikidata|qualifier|single|P548=Q2804309|P348|P577}}}}
| latest preview version = {{wikidata|property|edit|reference|P548=Q3295609|P348}}
| latest preview date = {{start date and age|{{wikidata|qualifier|single|P548=Q3295609|P348|P577}}}}
| typing = [[Static typing|Static]], [[Dynamic typing|dynamic]],<ref name="dynamic" /> [[Strong and weak typing|strong]], [[Type system#Safely and unsafely typed systems|safe]], [[Nominative type system|nominative]], [[Type inference|partly inferred]]
| memory management = [[Garbage collection (computer science)|automatic memory management]]
| implementations = [[Microsoft Visual C Sharp|Visual C#]], [[.NET]], [[Mono (software)|Mono]], [[Universal Windows Platform]]<br/>'''Discontinued''': [[.NET Framework]], [[DotGNU]]
| dialects = [[Cω]], [[Polyphonic C Sharp|Polyphonic C#]], [http://ecsharp.net Enhanced C#]
| influenced_by = [[C++]],<ref name="influenced by CPP" /> [[Cω]], [[Eiffel (programming language)|Eiffel]], [[F Sharp (programming language)|F#]],{{efn|for async}} [[Haskell]], [[Scala (programming language)|Scala]], [[Icon (programming language)|Icon]], [[J Sharp|J#]], [[Visual J++|J++]], [[Java (programming language)|Java]],<ref name="influenced by CPP" /> [[JavaScript]]<!--var-->, [[ML (programming language)|ML]], [[Modula-3]], [[Object Pascal]],<ref name="influenced by op" /> [[Visual Basic|VB]]
| influenced = [[Chapel (programming language)|Chapel]],<ref name="chplspec">{{cite web|title=Chapel spec (Acknowledgments)|url=http://chapel.cray.com/spec/spec-0.98.pdf|date=2015-10-01|access-date=2016-01-14|publisher=Cray Inc|archive-date=February 5, 2016|archive-url=https://web.archive.org/web/20160205114946/http://chapel.cray.com/spec/spec-0.98.pdf|url-status=dead}}</ref> [[Clojure]],<ref>{{cite web |url=http://www.codequarterly.com/2011/rich-hickey|archive-url=https://web.archive.org/web/20170111184835/http://www.codequarterly.com/2011/rich-hickey|url-status=dead|archive-date=2017-01-11|title=Rich Hickey Q&A by Michael Fogus|access-date=2017-01-11}}</ref> [[Crystal (programming language)|Crystal]],<ref name="rel_0.18.0">{{cite web
| url = http://crystal-lang.org/2016/06/14/crystal-0.18.0-released.html#comment-2732771703
| title = Crystal 0.18.0 released!
| last = Borenszweig
| first = Ary
| date = June 14, 2016
| quote = It's heavily inspired by Ruby, and other languages (like C#, Go and Python).
| access-date = August 7, 2017
| archive-date = December 25, 2018
| archive-url = https://web.archive.org/web/20181225175315/https://crystal-lang.org/2016/06/14/crystal-0.18.0-released.html#comment-2732771703
| url-status = live
}}</ref> [[D (programming language)|D]], [[J Sharp|J#]], [[Dart (programming language)|Dart]],<ref>{{cite web|title=Web Languages and VMs: Fast Code is Always in Fashion. (V8, Dart) - Google I/O 2013|website = [[YouTube]]| date=May 16, 2013 |url=https://www.youtube.com/watch?v=huawCRlo9H4&t=30m10s |archive-url=https://ghostarchive.org/varchive/youtube/20211221/huawCRlo9H4 |archive-date=2021-12-21 |url-status=live|access-date=22 December 2013}}{{cbignore}}</ref> [[F Sharp (programming language)|F#]], [[Hack (programming language)|Hack]], [[Java (programming language)|Java]],<ref>Java 5.0 added several new language features (the [[foreach loop|enhanced for loop]], [[Object type (object-oriented programming)#Autoboxing|autoboxing]], [[variadic function|varargs]] and [[Java annotation|annotations]]), after they were introduced in the similar (and competing) C# language [http://www.barrycornelius.com/papers/java5/] {{Webarchive|url=https://web.archive.org/web/20110319065438/http://www.barrycornelius.com/papers/java5/ |date=March 19, 2011 }} [http://www.levenez.com/lang/] {{Webarchive|url=https://web.archive.org/web/20060107162045/http://www.levenez.com/lang/ |date=January 7, 2006 }}</ref><ref name="influenced" /> [[Kotlin (programming language)|Kotlin]], [[Nemerle]], [[Oxygene (programming language)|Oxygene]], [[Rust (programming language)|Rust]],<ref>{{Cite web |url=https://doc.rust-lang.org/reference/influences.html |title=Influences - The Rust Reference |website=The Rust Reference |access-date=2023-04-18 |archive-date=January 26, 2019 |archive-url=https://web.archive.org/web/20190126051127/https://doc.rust-lang.org/reference/influences.html |url-status=live }}</ref> [[Swift (programming language)|Swift]],<ref name="lattner2014">{{cite web|url=http://nondot.org/sabre/|title=Chris Lattner's Homepage|last=Lattner|first=Chris|date=2014-06-03|access-date=2020-05-12|publisher=Chris Lattner|quote=The Swift language is the product of tireless effort from a team of language experts, documentation gurus, compiler optimization ninjas, and an incredibly important internal dogfooding group who provided feedback to help refine and battle-test ideas. Of course, it also greatly benefited from the experiences hard-won by many other languages in the field, drawing ideas from Objective-C, Rust, Haskell, Ruby, Python, C#, CLU, and far too many others to list.|archive-date=December 25, 2018|archive-url=https://web.archive.org/web/20181225175312/http://nondot.org/sabre/|url-status=live}}</ref> [[Vala (programming language)|Vala]], [[TypeScript]]
| platform = [[Common Language Infrastructure]]
| license = {{plainlist|
*[[Roslyn (compiler)|Roslyn]] compiler: [[MIT License|MIT/X11]]<ref name="auto">{{Cite web|url=https://github.com/dotnet/roslyn|title=The Roslyn .NET compiler provides C# and Visual Basic languages with rich code analysis APIs.: dotnet/roslyn|date=November 13, 2019|via=GitHub|access-date=February 13, 2015|archive-date=February 22, 2021|archive-url=https://web.archive.org/web/20210222190922/https://github.com/dotnet/roslyn|url-status=live}}</ref>
*[[.NET Core|.NET Core CLR]]: [[MIT License|MIT/X11]]<ref>{{Cite web|url=https://github.com/dotnet/coreclr|title=CoreCLR is the runtime for .NET Core. It includes the garbage collector, JIT compiler, primitive data types and low-level classes.: dotnet/coreclr|date=November 13, 2019|via=GitHub|access-date=March 8, 2017|archive-date=October 14, 2019|archive-url=https://web.archive.org/web/20191014104939/https://github.com/dotnet/coreclr|url-status=live}}</ref>
*[[Mono (software)|Mono]] compiler: dual [[GPLv3]] and MIT/X11
*[[DotGNU]]: dual [[GPL]] and [[LGPL]]
}}
| file_ext = <code>.cs</code>, <code>.csx</code>
| website = {{URL|https://learn.microsoft.com/en-us/dotnet/csharp/}}
| wikibooks = C Sharp Programming
}}
'''C#''' ({{IPAc-en|,|s|i:|_|'|sh|a:r|p}} {{respell|see|_|SHARP}}){{efn|By convention, a [[number sign]] is used for the second character in normal text; in artistic representations, sometimes a true [[♯|sharp sign]] is used: C♯. However the [[Ecma International|ECMA]] 334 standard states: "The name C# is written as the LATIN CAPITAL LETTER C (U+0043) followed by the NUMBER SIGN # (U+0023)."}} is a [[General-purpose programming language|general-purpose]] [[High-level programming language|high-level]] [[programming language]] supporting multiple [[Programming paradigm|paradigm]]s. C# encompasses static typing,{{sfn|Skeet|2019}}{{rp|4}} [[Strong and weak typing|strong typing]], [[lexically scoped]], [[Imperative programming|imperative]], [[Declarative programming|declarative]], [[Functional programming|functional]], [[Generic programming|generic]],{{sfn|Skeet|2019}}{{rp|22}} [[Object-oriented programming|object-oriented]] ([[Class (computer programming)|class]]-based), and [[Component-based software engineering|component-oriented]] programming disciplines.<ref name="ECMA-334" />
 
The principal inventors of the C# programming language were [[Anders Hejlsberg]], Scott Wiltamuth, and Peter Golde from [[Microsoft]].<ref name="ECMA-334" /> It was first widely distributed in July 2000<ref name="ECMA-334" /> and was later approved as an [[international standard]] by [[Ecma International|Ecma]] (ECMA-334) in 2002 and [[International Organization for Standardization|ISO]]/[[International Electrotechnical Commission|IEC]] (ISO/IEC 23270 and 20619{{efn|Language versions 1.0, 2.0, and 5.0 are available as ISO/IEC 23270. Beginning with version 7.0, the specification is available as ISO/IEC 20619}}) in 2003. Microsoft introduced C# along with [[.NET Framework]] and Microsoft [[Visual Studio]], both of which are technically speaking, [[Proprietary software|closed-source]]. At the time, Microsoft had no open-source products. Four years later, in 2004, a [[free and open-source]] project called Microsoft [[Mono (software)|Mono]] began, providing a [[cross-platform]] [[compiler]] and [[runtime environment]] for the C# programming language. A decade later, Microsoft released [[Visual Studio Code]] (code editor), [[Roslyn (compiler)|Roslyn]] (compiler), and [[.NET|the unified .NET platform]] (software framework), all of which support C# and are free, open-source, and cross-platform. Mono also joined Microsoft but was not merged into .NET.
'''C#''' ([[#Language name|see section on naming, pronunciation]]) is an [[object-oriented programming|object-oriented]] [[programming language]] developed by [[Microsoft]] as part of their [[Microsoft .NET|.NET]] initiative. Microsoft based C# on [[C plus plus|C++]] and [[Java programming language|Java]]. C# was designed as a language that would provide [[syntax]] that would be comfortable for C++ and Java programmers, with [[rapid application development|rapid development]] functionality that would suit [[Visual Basic]] and [[Delphi programming language|Delphi]] programmers.
 
{{As of|January 2025|post=,}} the most recent stable version of the language is C# 13.0, which was released in 2024 in .NET 9.0<ref>{{Cite web |last=Dollard |first=Kathleen |date=2023-11-14 |title=Announcing C# 12 |url=https://devblogs.microsoft.com/dotnet/announcing-csharp-12/ |access-date=2023-11-18 |website=.NET Blog |language=en-US |archive-date=November 18, 2023 |archive-url=https://web.archive.org/web/20231118121012/https://devblogs.microsoft.com/dotnet/announcing-csharp-12/ |url-status=live }}</ref><ref>{{Cite web |last=Seth |first=Gaurav |date=2023-11-14 |title=Announcing .NET 8 |url=https://devblogs.microsoft.com/dotnet/announcing-dotnet-8/ |access-date=2023-11-18 |website=.NET Blog |language=en-US |archive-date=November 19, 2023 |archive-url=https://web.archive.org/web/20231119051129/https://devblogs.microsoft.com/dotnet/announcing-dotnet-8/ |url-status=live }}</ref>
== Language features ==
 
==Design goals==
C# is, in some sense, the programming language which most directly reflects the underlying .NET Framework on which all .NET programs run, and it depends strongly on this framework; there is no such thing as an [http://msdn.microsoft.com/library/en-us/csref/html/vcwlkunsafecodetutorial.asp unmanaged C# program]. Its primitive datatypes are objects of the corresponding .NET types, it is [[garbage collection (computer science)|garbage-collected]], and many of its abstractions, such as its classes, interfaces, delegates, exceptions, and so on, expose explicit features of the .NET runtime.
The Ecma standard lists these design goals for C#:<ref name="ECMA-334">{{cite book |url=https://www.ecma-international.org/wp-content/uploads/ECMA-334_4th_edition_june_2006.pdf |title=C# Language Specification |date=June 2006 |publisher=[[Ecma International]] |edition=4th |language=en-US |access-date=January 26, 2012 |archive-date=April 21, 2021 |archive-url=https://web.archive.org/web/20210421135433/https://www.ecma-international.org/wp-content/uploads/ECMA-334_4th_edition_june_2006.pdf |url-status=live }}</ref>
 
* The language is intended to be a simple, modern, general-purpose, [[Object-oriented programming|object-oriented]] programming language.
Compared to C and C++, the language is restricted or enhanced in a number of ways, including but not limited to the following:
* The language, and implementations thereof, should provide support for software engineering principles such as [[Strong and weak typing|strong type]] checking, array [[bounds checking]],{{sfn|Albahari|2022}}{{rp|58–59}} detection of attempts to use [[uninitialized variable]]s, and automatic [[Garbage collection (computer science)|garbage collection]].{{sfn|Albahari|2022}}{{rp|563}} Software robustness, durability, and programmer productivity are important.
* Raw pointers can only be used in a special ''unsafe mode''. Most object access is done through safe references, which cannot be made invalid, and most arithmetic is checked for overflow. Pointers can only be made to so-called ''value types''; objects managed by the garbage collector can only be ''referred'' to.
* The language is intended for use in developing [[software components]] suitable for [[Deployment environment|deployment]] in distributed environments.
* Objects cannot be explicitly freed, but instead are garbage collected when no more references to them exist. (Objects representing unmanaged resources, though, can be instructed to release those resources through the standard <code>IDisposable</code> interface.)
* [[Software portability|Portability]] is very important for [[source code]] and [[programmer]]s, especially those already familiar with [[C (programming language)|C]] and [[C++]].
* Only single inheritance is available, but a class can implement any number of abstract interfaces. This functions mainly to simplify the runtime's implementation.
* Support for [[internationalization and localization|internationalization]]{{sfn|Albahari|2022}}{{rp|314}} is very important.
* 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. There are no implicit conversions between booleans and integers, between enumeration members and integers, no void pointers (although references to ''Object'' are similar), and any user-defined implicit conversion must be explicitly marked as such, unlike C++'s [[copy constructor|copy constructors]].
* C# is intended to be suitable for writing applications for both hosted and [[embedded system]]s, ranging from the very large that use sophisticated [[operating system]]s, down to the very small having dedicated functions.
* Syntax for [[array]] [[declaration]] is different ("<code>int[] a = new int[5]</code>" instead of "<code>int a[5]</code>").
* Although C# applications are intended to be economical with regard to memory and [[processing power]] requirements, the language was not intended to compete directly on performance and size with C or assembly language.<ref>{{Cite web|title=Design Goals of C#|url=https://www.java-samples.com/showtutorial.php?tutorialid=1425|access-date=2021-10-06|website=www.java-samples.com|archive-date=October 6, 2021|archive-url=https://web.archive.org/web/20211006065344/https://www.java-samples.com/showtutorial.php?tutorialid=1425|url-status=live}}</ref>
* [[Enumeration]] members are placed in their own [[namespace]].
* C# has no [[Generic programming#Templates|templates]].
* Properties are available, which enable methods to be called using syntax that resembles data member access.
* Full [[reflection (computer science)|reflection]] is available.
 
==History==
=== C# 2.0 new language features ===
{{Multiple image
New features in C# 2.0 are:
| footer = C#'s former logos
* [[Partial type]]s (separation of class implementation into more than one file)
|image1 = Logo C sharp.svg
* [[Generic programming|Generics]] or parameterized types. They support some features not supported by C++ templates such as type constraints on generic parameters. 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 citizens in the Virtual Machine, which allows for optimizations and preservation of the type information. See [[Insertion_sort_implementations#C.23_2.0|a simple example of C# 2.0 generics]].
|width1 = 90
* A new form of [[iterator]] that employs [[coroutine]]s via a functional-style <code>yield</code> keyword similar to <code>yield</code> in [[Python programming language|Python]]
|image2 = C Sharp wordmark.svg
* [[Anonymous method]]s providing [[closure (computer science)|closure]] functionality
|width2 = 100
* Nullable value types (denoted by a question mark, ie 'int? i = null;', allowing improved interaction with SQL databases
}}
During the development of the [[.NET Framework]], the [[Base Class Library|class libraries]] were originally written using a [[managed code]] compiler system named ''Simple Managed C'' (SMC).<ref>{{cite web
|url= https://docs.microsoft.com/en-us/archive/blogs/jasonz/couple-of-historical-facts
|title= Couple of Historical Facts
|first= Jason
|last= Zander
|date= 2007-11-22
|access-date= 2009-02-23
|archive-date= 2020-07-29
|archive-url= https://web.archive.org/web/20200729002618/https://docs.microsoft.com/en-us/archive/blogs/jasonz/couple-of-historical-facts
|url-status= live
}}</ref><ref>{{cite web
|url= http://aspadvice.com/blogs/rbirkby/archive/2006/11/28/What-language-was-ASP.Net-originally-written-in_3F00_.aspx
|archive-url= https://web.archive.org/web/20160624010356/http://aspadvice.com/blogs/rbirkby/archive/2006/11/28/What-language-was-ASP.Net-originally-written-in_3F00_.aspx
|archive-date= 2016-06-24
|title= What language was ASP.Net originally written in?
|date= 2006-11-28
|first= Scott
|last= Guthrie
|author-link= Scott Guthrie
|access-date= 2008-02-21
}}</ref> In January 1999, [[Anders Hejlsberg]] formed a team to build a new language at the time called COOL, which stood for "[[List of C-family programming languages|C-like]] Object Oriented Language".<ref name="computerworld2008">{{cite magazine
|url= https://www.computerworld.com.au/article/261958/a-z_programming_languages_c_/
|title= The A-Z of Programming Languages: C#
|first= Naomi
|last= Hamilton
|magazine= [[Computerworld]]
|date= 2008-10-01
|access-date= 2008-10-01
|archive-url=https://web.archive.org/web/20190518115808/https://www.computerworld.com.au/article/261958/a-z_programming_languages_c_/
|archive-date=2019-05-18 |url-status=dead}}</ref>
 
Microsoft had considered keeping the name "COOL(C-like Object Oriented Language)" as the final name of the language, but chose not to do so for trademark reasons. By the time the .NET project was publicly announced at the July 2000 [[Professional Developers Conference]], the language had been renamed C#, and the class libraries and [[ASP.NET]] runtime were ported to C#.{{fact|date=July 2025}}
[[Anders Hejlsberg]], C#'s creator, discusses the difference between the implementations of generics in C#, Java, and C++ in [http://www.artima.com/intv/generics2.html this interview].
 
Hejlsberg was C#'s principal designer and lead architect at Microsoft, and had been previously involved with the design of [[Turbo Pascal]], [[Embarcadero Technologies|Embarcadero]] [[Delphi (software)|Delphi]] (formerly [[CodeGear]] Delphi, [[Inprise]] Delphi and [[Borland]] Delphi), and [[Visual J++]]. In interviews and technical papers, he has stated that flaws in most major programming languages (e.g. [[C++]], [[Java (programming language)|Java]], [[Delphi (software)|Delphi]], and [[Smalltalk]]) drove the fundamentals of the [[Common Language Runtime]] (CLR), which, in turn, drove the design of the C# language.<ref>{{Cite web |title=Details |url=http://nilsnaegele.com/techreview/Reviews/Details/1 |archive-url=https://web.archive.org/web/20190407173805/http://nilsnaegele.com/techreview/Reviews/Details/1 |archive-date=2019-04-07 |access-date=2019-04-07 |url-status=usurped |website=nilsnaegele.com}}</ref>
Nullable types received an 11th hour improvement at the end of August 2005 (only weeks before the official launch), to improve their [[Boxing (Computer science)|boxing]] characteristics: a nullable variable which is assigned null is not actually a null reference (it's a value type). Hence boxing this value would result in a non-null reference! The following code illustrates the flaw:
 
[[James Gosling]], who created the [[Java (programming language)|Java]] programming language in 1994, and [[Bill Joy]], a co-founder of [[Sun Microsystems]], the originator of Java, called C# an "imitation" of Java; Gosling further said: "[C# is] sort of Java with reliability, productivity and security deleted."<ref name="gosling">{{cite web
int? i = null;
|url=https://www.cnet.com/tech/tech-industry/why-microsofts-c-isnt/
object o = i;
|title=Why Microsoft's C# isn't
if (o == null)
|publisher=CNET: CBS Interactive
Console.WriteLine("Correct behaviour - you are running a version from Sept 05 or later");
|year=2002
else
|access-date=2023-09-18
Console.WriteLine("Incorrect behaviour, prior to Sept 05 releases");
|archive-date=2023-08-14
|archive-url=https://web.archive.org/web/20230814054213/https://www.cnet.com/tech/tech-industry/why-microsofts-c-isnt/
|url-status=live
}}</ref><ref>{{cite web
|url= https://www.cnet.com/tech/tech-industry/microsofts-blind-spot/
|title= Microsoft's blind spot
|first= Bill
|last= Joy
|publisher= cnet.com
|date= 2002-02-07
|access-date= 2023-09-18
|author-link= Bill Joy
|archive-date= 2023-08-14
|archive-url= https://web.archive.org/web/20230814053108/https://www.cnet.com/tech/tech-industry/microsofts-blind-spot/
|url-status= live
}}</ref>
 
In July 2000, Hejlsberg said that C# is "not a Java clone" and is "much closer to C++" in its design.<ref name="JohnOsborn">{{Cite news
The late nature of this fix caused some controversy, since it required core-[[Common Language Runtime|CLR]] changes affecting not only .NET2, but all dependent technologies (including C#, VB, SQL Server 2005 and Visual Studio 2005).
|last= Osborn
|first= John
|date= 2000-08-01
|url= http://windowsdevcenter.com/pub/a/oreilly/windows/news/hejlsberg_0800.html
|title= Deep Inside C#: An Interview with Microsoft Chief Architect Anders Hejlsberg
|publisher= O'Reilly Media
|access-date= 2009-11-14
|archive-date= 2010-01-09
|archive-url= https://web.archive.org/web/20100109195800/http://windowsdevcenter.com/pub/a/oreilly/windows/news/hejlsberg_0800.html
|url-status= live
}}</ref>
 
Since the release of C# 2.0 in November 2005, the C# and Java languages have evolved on increasingly divergent trajectories, becoming two quite different languages. One of the first major departures came with the addition of [[Generic programming|generics]] to both languages, with vastly different implementations. C# uses [[Reification (computer science)|reification]] to provide "first-class" generic objects that can be used like any other class, with [[code generation (compiler)|code generation]] performed at class-load time.<ref>{{cite web
=== C# 3.0 new language features ===
| url = http://msdn.microsoft.com/en-us/library/512aeb7t.aspx
In C# 3.0 there will be radical additions:
| title = Generics (C# Programming Guide)
* "<code>select</code>, <code>from</code>, <code>where</code>" keywords allowing to query from collections, sql and more (called LINQ - Language INtegrated Query)
| publisher = Microsoft
* Object initialization : <code>Customer c = new Customer(); c.Name="James";</code> becomes <code>Customer c = new Customer { Name="James" };</code>
| access-date = 2011-03-21
* Lambda expressions : <code>listOfFoo.Where(delegate(Foo x) { return x.size>10;})</code> becomes <code>listOfFoo.Where(x => x.size>10);</code>
| archive-date = 2011-08-26
* Local variable type inference: <code>var x = "hello";</code> is interchangeable with <code>string x = "hello";</code>
| archive-url = https://web.archive.org/web/20110826233800/http://msdn.microsoft.com/en-us/library/512aeb7t.aspx
* Extension methods (adding methods to classes by including the <code>this</code> keyword in the first parameter)
| url-status = live
}}</ref>
 
C# has also added several major features to accommodate functional-style programming, culminating in the [[Language Integrated Query|LINQ]] extensions released with C# 3.0 and its supporting framework of [[Anonymous function|lambda expressions]], [[extension method]]s, and [[anonymous type]]s.<ref>{{cite web
C# 3.0 was unveiled at the PDC 2005, and a Preview, with specifications is available [http://msdn.microsoft.com/netframework/future/linq/ From the MSDN Page (MSDN)].
| url = http://msdn.microsoft.com/en-us/library/bb308959.aspx
| title = LINQ: .NET Language-Integrated Query
| author = Don Box and Anders Hejlsberg
| publisher = Microsoft
| date = February 2007
| access-date = 2011-03-21
| archive-date = 2011-08-24
| archive-url = https://web.archive.org/web/20110824063725/http://msdn.microsoft.com/en-us/library/bb308959.aspx
| url-status = live
}}</ref> These features enable C# programmers to use functional programming techniques, such as [[Closure (computer science)|closures]], when it is advantageous to their application. The LINQ extensions and the functional imports help developers reduce the amount of [[boilerplate code]] included in common tasks such as querying a database, parsing an XML file, or searching through a data structure, shifting the emphasis onto the actual program logic to help improve readability and maintainability.<ref>{{cite web
| url = http://blog.abodit.com/2010/04/why-functional-programming-is-better-linq-c-sharp-than-procedural-code/
| title = Why functional programming and LINQ is often better than procedural code
| last = Mercer
| first = Ian
| publisher = abodit.com
| date = 2010-04-15
| access-date = 2011-03-21
| archive-date = 2011-07-11
| archive-url = https://web.archive.org/web/20110711124734/http://blog.abodit.com/2010/04/why-functional-programming-is-better-linq-c-sharp-than-procedural-code/
| url-status = dead
}}</ref>
 
C# used to have a [[mascot]] called Andy (named after [[Anders Hejlsberg]]). It was retired on January 29, 2004.<ref>{{cite web|url=http://blogs.msdn.com/b/danielfe/archive/2004/01/29/64429.aspx |title=Andy Retires |work=Dan Fernandez's Blog |publisher=Blogs.msdn.com |date=2004-01-29 |access-date=2012-10-04 |archive-url=https://web.archive.org/web/20160119144858if_/http://blogs.msdn.com/b/danielfe/archive/2004/01/29/64429.aspx|archive-date=2016-01-19 |first=Dan |last=Fernandez }}</ref>
Language researchers at Microsoft have emphasized that C# 3.0 is bytecode-compatible with C# 2.0 &mdash; essentially the improvements are purely syntactic or compile-time improvements. For example, many of the most common integrated queries can already be implemented using anonymous delegates in combination with predicate-based container methods such as <code>List.FindAll</code> and <code>List.RemoveAll</code>.
 
C# was originally submitted to the ISO/IEC JTC 1 subcommittee [[ISO/IEC JTC 1/SC 22|SC 22]] for review,<ref>{{cite web |url=http://www.iso.org/iso/iso_technical_committee.html?commid=45202 |title=Technical committees - JTC 1/SC 22 - Programming languages, their environments and system software interfaces |publisher=ISO |access-date=October 4, 2012 |archive-date=September 27, 2012 |archive-url=https://web.archive.org/web/20120927020608/http://www.iso.org/iso/iso_technical_committee.html?commid=45202 |url-status=live }}</ref> under ISO/IEC 23270:2003,<ref>{{cite web |url=http://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=36768 |title=ISO/IEC 23270:2003 - Information technology - C# Language Specification |publisher=Iso.org |date=August 23, 2006 |access-date=October 4, 2012 |archive-url=https://web.archive.org/web/20120508100146/http://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=36768 |archive-date=May 8, 2012 |url-status=dead }}</ref> was withdrawn and was then approved under ISO/IEC 23270:2006.<ref>{{cite web |url=http://www.iso.org/iso/iso_catalogue/catalogue_ics/catalogue_detail_ics.htm?csnumber=42926 |title=ISO/IEC 23270:2006 - Information technology - Programming languages - C# |publisher=Iso.org |date=January 26, 2012 |access-date=October 4, 2012 |archive-date=December 6, 2010 |archive-url=https://web.archive.org/web/20101206152217/http://www.iso.org/iso/iso_catalogue/catalogue_ics/catalogue_detail_ics.htm?csnumber=42926 |url-status=live }}</ref> The 23270:2006 is withdrawn under 23270:2018 and approved with this version.<ref>{{Cite web|title=SO/IEC 23270:2018 Information technology — Programming languages — C#|url=https://www.iso.org/cms/render/live/en/sites/isoorg/contents/data/standard/07/51/75178.html|access-date=2020-11-26|website=ISO|language=en}}</ref>
== Code libraries ==
 
===Name===
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.
[[Microsoft]] first used the name C# in 1988 for a variant of the C language designed for incremental compilation.<ref>{{cite web|last1=Mariani|first1=Rico|title=My History of Visual Studio (Part 1) – Rico Mariani's Performance Tidbits|url=https://blogs.msdn.microsoft.com/ricom/2009/10/05/my-history-of-visual-studio-part-1/|website=Rico Mariani's Performance Tidbits|date=October 5, 2009|access-date=May 26, 2018|archive-date=May 27, 2018|archive-url=https://web.archive.org/web/20180527120755/https://blogs.msdn.microsoft.com/ricom/2009/10/05/my-history-of-visual-studio-part-1/|url-status=live}}</ref> That project was not completed, and the name was later reused.
 
{{stack|[[File:Treblecsharp5.svg|thumb|100px|[[C♯ (musical note)|C-sharp musical note]]]]}}
The .NET Framework is a [[class (computer science)|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]]s (ASP.NET), [[XML]] parsing and [[Reflection (computer science)|reflection]]. The code is organized into a set of [[Namespace (programming)|namespace]]s which group together classes with a similar function, e.g. <code>System.Drawing</code> for graphics, <code>System.Collections</code> for data structures and <code>System.Windows.Forms</code> for the Windows Forms system.
The name "C sharp" was inspired by the musical notation whereby a [[Sharp (music)|sharp symbol]] indicates that the written note should be made a [[semitone]] higher in [[Pitch (music)|pitch]].<ref>{{cite web
|url= http://www.jameskovacs.com/blog/CNETHistoryLesson.aspx
|title= C#/.NET History Lesson
|first= James
|last= Kovacs
|date= September 7, 2007
|access-date= June 18, 2009
|archive-date= March 6, 2009
|archive-url= https://web.archive.org/web/20090306073219/http://jameskovacs.com/blog/CNETHistoryLesson.aspx
|url-status= dead
}}</ref>
This is similar to the language name of [[C++]], where "++" indicates that a variable should be incremented by 1 after being evaluated. The sharp symbol also resembles a [[Typographic ligature|ligature]] of four "+" symbols (in a two-by-two grid), further implying that the language is an increment of C++.<ref>{{cite magazine
|url= http://www.computerworld.com.au/article/261958/a-z_programming_languages_c_/?pp=2
|title= The A-Z of Programming Languages: C#
|first= Anders
|last= Hejlsberg
|magazine= [[Computerworld]]
|date= October 1, 2008
|access-date= June 22, 2014
|archive-date= April 2, 2015
|archive-url= https://web.archive.org/web/20150402120752/https://www.computerworld.com.au/article/261958/a-z_programming_languages_c_/?pp=2
|url-status= dead
}}</ref>
 
Due to technical limits of display (standard fonts, browsers, etc.), and most [[keyboard layout]]s lacking a sharp symbol ({{unichar|266F|MUSIC SHARP SIGN|html=|nlink=Sharp (music)}}), the [[number sign]] ({{unichar|0023|NUMBER SIGN|html=}}) was chosen to approximate the sharp symbol in the written name of the programming language.<ref name="MS CSharp FAQ">{{cite web
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 (through al.exe) 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 (known as mscorlib.dll in Microsoft's implementation).
|url=http://msdn.microsoft.com/vcsharp/previous/2002/FAQ/default.aspx
|title=Microsoft C# FAQ
|publisher=[[Microsoft]]
|access-date=March 25, 2008
|url-status=dead
|archive-url=https://web.archive.org/web/20060214002638/http://msdn.microsoft.com/vcsharp/previous/2002/FAQ/default.aspx
|archive-date=February 14, 2006
|df=mdy
}}</ref>
This convention is reflected in the ECMA-334 C# Language Specification.<ref name="ECMA-334"/>
 
The "sharp" suffix has been used by a number of other Microsoft [[.NET]] compatible/compliant languages that are variants of existing languages, including [[J Sharp|J#]] (a .NET language also designed by Microsoft that is derived from [[Java (programming language)|Java]] 1.1), [[A Sharp (.NET)|A#]] (from [[Ada (programming language)|Ada]]), and the [[functional programming]] language [[F Sharp (programming language)|F#]].<ref name="MS FSharp FAQ">{{cite web
== Hello world example ==
|url=http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/faq.aspx
|title=F# FAQ
|publisher=Microsoft Research
|access-date=June 18, 2009
|url-status=dead
|archive-url=https://web.archive.org/web/20090218222543/http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/faq.aspx
|archive-date=February 18, 2009
|df=mdy
}}</ref> The original implementation of [[EiffelStudio|Eiffel for .NET]] was called [[EiffelStudio|Eiffel#]],<ref>{{cite web
|url= http://msdn.microsoft.com/en-us/library/ms973898.aspx
|title= Full Eiffel on the .NET Framework
|date= June 2002
|first1= Raphael
|last1= Simon
|first2= Emmanuel
|last2= Stapf
|first3= Bertrand
|last3= Meyer
|publisher= [[Microsoft]]
|access-date= June 18, 2009
|archive-date= July 21, 2009
|archive-url= https://web.archive.org/web/20090721131102/http://msdn.microsoft.com/en-us/library/ms973898.aspx
|url-status= live
}}</ref> a name retired since the full [[Eiffel (programming language)|Eiffel]] language is now supported. The suffix has also been used for [[Library (computing)|libraries]], such as [[Gtk Sharp|Gtk#]] (a .NET [[Wrapper pattern|wrapper]] for [[GTK]] and other [[GNOME]] libraries) and [[Cocoa Sharp|Cocoa#]] (a wrapper for [[Cocoa (API)|Cocoa]]).
 
===Versions===
The following is a very simple C# program, a version of the classic "[[hello world]]" example.
Development of the text for standards (beginning with C#&nbsp;6) is done on [https://github.com/dotnet/csharpstandard GitHub]. C#&nbsp;7 was submitted to [[Ecma International|Ecma]] and approved in December 2023. As of January 2024, the standard for C#&nbsp;8 is currently under development, referencing the [https://github.com/dotnet/csharplang/tree/main/proposals approved language proposals].
 
{| class="wikitable"
'''public''' '''class''' ExampleClass
|-
{
! scope="col" rowspan="2" | C#<br/>version
'''public''' '''static''' '''void''' Main()
! scope="colgroup" colspan="3" | Language specification
{
! scope="col" rowspan="2" | Date
System.Console.WriteLine("Hello world!");
! scope="col" rowspan="2" | .NET
}
! scope="col" rowspan="2" | [[Visual Studio]]
}
|-
! scope="col" | [[Ecma International|Ecma]]
! scope="col" | [[ISO/IEC]]
! scope="col" | [[Microsoft]]
|-
| scope="row" | 1.0
| rowspan="2" | ECMA-334:2003, [https://ecma-international.org/wp-content/uploads/ECMA-334_2nd_edition_december_2002.pdf December 2002]
| rowspan="2" | ISO/IEC 23270:2003, [https://store.accuristech.com/ieee/standards/incits-iso-iec-23270-2003?product_id=1157805 April 2003]
| [http://download.microsoft.com/download/a/9/e/a9e229b9-fee5-4c3e-8476-917dee385062/CSharp%20Language%20Specification%20v1.0.doc January 2002]
| January 2002
| [[.NET Framework version history#.NET Framework 1.0|.NET Framework 1.0]]
| [[Visual Studio .NET|Visual Studio .NET 2002]]
|-
| scope="row" | 1.1<br/>1.2
| [http://download.microsoft.com/download/5/e/5/5e58be0a-b02b-41ac-a4a3-7a22286214ff/csharp%20language%20specification%20v1.2.doc October 2003]
| April 2003
| {{ubl|[[.NET Framework 1.1]]}}
| [[Visual Studio .NET 2003]]
|-
| scope="row" | [[C Sharp 2.0|2.0]]<ref>{{cite web|title=What's new in the C# 2.0 Language and Compiler|url=http://msdn.microsoft.com/en-us/library/7cz8t42e(v=vs.80).aspx|publisher=Microsoft|archive-url = https://web.archive.org/web/20101218191709/http://msdn.microsoft.com/en-us/library/7cz8t42e(v=vs.80).aspx|access-date=11 June 2014|archive-date = December 18, 2010}}</ref>
| ECMA-334:2006, [https://ecma-international.org/wp-content/uploads/ECMA-334_4th_edition_june_2006.pdf June 2006]
| ISO/IEC 23270:2006, [http://standards.iso.org/ittf/PubliclyAvailableStandards/c042926_ISO_IEC_23270_2006(E).zip September 2006]
| [http://download.microsoft.com/download/9/8/f/98fdf0c7-2bbd-40d3-9fd1-5a4159fa8044/csharp%202.0%20specification_sept_2005.doc September 2005]{{efn|The Microsoft C# 2.0 specification document only contains the new 2.0 features. For older features, use the 1.2 specification above.}}
| November 2005
| {{ubl|[[.NET Framework 2.0]]|[[.NET Framework 3.0]]}}
| [[Visual Studio 2005]]<br />[[Visual Studio 2008]]
|-
| scope="row" | [[C Sharp 3.0|3.0]]<ref>{{cite web|last1=Hejlsberg|first1=Anders|last2=Torgersen|first2=Mads|title=Overview of C# 3.0|url=http://msdn.microsoft.com/en-us/library/bb308966.aspx|website=Microsoft Developer Network|date=April 30, 2007|publisher=Microsoft|access-date=11 June 2014|archive-date=June 25, 2014|archive-url=https://web.archive.org/web/20140625123055/http://msdn.microsoft.com/en-us/library/bb308966.aspx|url-status=live}}</ref>
| colspan="2" rowspan="2" {{no|None}}
| [http://download.microsoft.com/download/3/8/8/388e7205-bc10-4226-b2a8-75351c669b09/CSharp%20Language%20Specification.doc August 2007]
| November 2007
| {{ubl|.NET Framework 2.0 (Except LINQ)<ref name="danielmoth1">{{cite web |url=http://www.danielmoth.com/Blog/using-c-30-from-net-20.aspx |title=Using C# 3.0 from .NET 2.0 |publisher=Danielmoth.com |date=May 13, 2007 |access-date=October 4, 2012 |archive-date=September 29, 2012 |archive-url=https://web.archive.org/web/20120929075553/http://www.danielmoth.com/Blog/Using-C-30-From-NET-20.aspx |url-status=live }}</ref>|.NET Framework 3.0 (Except LINQ)<ref name="danielmoth1"/>|[[.NET Framework 3.5]]}}
| [[Visual Studio 2008]]
|-
| scope="row" | [[C Sharp 4.0|4.0]]<ref>{{cite web|last=Hejlsberg|first=Anders|title=Future directions for C# and Visual Basic|url=http://channel9.msdn.com/Events/BUILD/BUILD2011/TOOL-816T|work=Channel 9 |series=BUILD2011 |publisher=Microsoft |date=September 15, 2011 |access-date=September 21, 2011|archive-date=September 23, 2011|archive-url=https://web.archive.org/web/20110923171150/http://channel9.msdn.com/Events/BUILD/BUILD2011/TOOL-816T|url-status=dead}}</ref>
| April 2010
| April 2010
| {{ubl|[[.NET Framework 4.0|.NET Framework 4]]}}
| [[Visual Studio 2010]]
|-
| scope="row" | 5.0<ref>{{cite web|title=An Introduction to New Features in C# 5.0|url=http://blogs.msdn.com/b/mvpawardprogram/archive/2012/03/26/introduction-of-new-features-in-c-5-0.aspx|website= The Microsoft MVP Award Program Blog |date=26 Mar 2012 |publisher=Microsoft|access-date=11 June 2014|url-status=dead|archive-date=June 4, 2014|archive-url=https://web.archive.org/web/20140604224114/http://blogs.msdn.com/b/mvpawardprogram/archive/2012/03/26/introduction-of-new-features-in-c-5-0.aspx}}</ref>
| ECMA-334:2017, [https://ecma-international.org/wp-content/uploads/ECMA-334_5th_edition_december_2017.pdf December 2017]
| ISO/IEC 23270:2018, [https://standards.iso.org/ittf/PubliclyAvailableStandards/c075178_ISO_IEC_23270_2018.zip December 2018]
| [https://www.microsoft.com/en-us/download/details.aspx?id=7029 June 2013]
| August 2012
| {{ubl|[[.NET Framework 4.5]]}}
| [[Visual Studio 2012]]<br />[[Visual Studio 2013]]
|-
| scope="row" | 6.0<ref>{{cite web|title=Languages features in C# 6 and VB 14 |url=https://github.com/dotnet/roslyn/wiki/Languages-features-in-C%23-6-and-VB-14|website=GitHub |publisher=dotnet/roslyn |access-date=13 February 2015|url-status=dead|archive-date=January 12, 2016|archive-url=https://web.archive.org/web/20160112082444/https://github.com/dotnet/roslyn/wiki/Languages-features-in-C%23-6-and-VB-14}}</ref>
| ECMA-334:2022, [https://ecma-international.org/wp-content/uploads/ECMA-334_6th_edition_june_2022.pdf June 2022]
| {{no|None}}
| [https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/ Draft]
| July 2015
| {{ubl|[[.NET Framework 4.6]]|.NET Core 1.0|.NET Core 1.1}}
| [[Visual Studio 2015]]
|-
| scope="row" | 7.0<ref>{{Cite web|url=https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7|title=What's new in C# 7|date=2016-12-21|website=Microsoft Docs |url-status=deviated |archive-url=https://web.archive.org/web/20171101224329/https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7 |archive-date= Nov 1, 2017 }}</ref><ref name="new_features_in_7">{{Cite web|title = New Features in C# 7.0|url = https://blogs.msdn.microsoft.com/dotnet/2017/03/09/new-features-in-c-7-0/|first1 = Mads|last1 = Torgersen|publisher = Microsoft|website = .NET Blog|date = March 9, 2017|access-date = 2017-06-09|archive-date = April 11, 2017|archive-url = https://web.archive.org/web/20170411055800/https://blogs.msdn.microsoft.com/dotnet/2017/03/09/new-features-in-c-7-0/|url-status = live}}</ref>
| rowspan=4 | ECMA-334:2023, [https://ecma-international.org/wp-content/uploads/ECMA-334_7th_edition_december_2023.pdf December 2023]
| rowspan=4 | ISO/IEC 20619:2023, [https://standards.iso.org/ittf/PubliclyAvailableStandards/ISO_IEC%2020619_2023%20ed.1%20-%20id.86347%20Publication%20PDF%20(en).zip September 2023]
| [https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-7.0/ Specification proposal]
| March 2017
| {{ubl|[[.NET Framework 4.7]]}}
| [[Visual Studio 2017]] version 15.0<ref>{{Cite web|url=https://learn.microsoft.com/en-us/visualstudio/releasenotes/vs2017-relnotes-v15.0|title=Visual Studio 2017 version 15.0 Release Notes|website=Microsoft Learn|date=April 11, 2023|access-date=2023-04-19|archive-date=April 20, 2023|archive-url=https://web.archive.org/web/20230420021649/https://learn.microsoft.com/en-us/visualstudio/releasenotes/vs2017-relnotes-v15.0|url-status=live}}</ref>
|-
| scope="row" | 7.1<ref>{{Cite web|url=https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7-1|title=What's new in C# 7.1|website=Microsoft Docs|access-date=2017-10-09|archive-date=October 10, 2017|archive-url=https://web.archive.org/web/20171010054644/https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7-1|url-status=live}}</ref>
| [https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-7.1/ Specification proposal]
| August 2017
| {{ubl|.NET Core 2.0}}
| [[Visual Studio 2017]] version 15.3<ref>{{Cite web|url=https://docs.microsoft.com/en-us/visualstudio/releasenotes/vs2017-relnotes-v15.3|title=Visual Studio 2017 version 15.3 Release Notes|website=Microsoft Learn|date=April 11, 2023 |access-date=2023-04-19 |url-status=live |archive-url= https://web.archive.org/web/20230321003648/https://learn.microsoft.com/en-us/visualstudio/releasenotes/vs2017-relnotes-v15.3 |archive-date= Mar 21, 2023 }}</ref>
|-
| scope="row" | 7.2<ref>{{Cite web|url=https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7-2|title=What's new in C# 7.2|website=Microsoft Docs|access-date=2017-11-26|archive-date=December 1, 2017|archive-url=https://web.archive.org/web/20171201080837/https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7-2|url-status=live}}</ref>
| [https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-7.2/ Specification proposal]
| November 2017
|
| [[Visual Studio 2017]] version 15.5<ref>{{Cite web|url=https://learn.microsoft.com/en-us/visualstudio/releasenotes/vs2017-relnotes-v15.5|title=Visual Studio 2017 version 15.5 Release Notes|website=Microsoft Learn|date=April 11, 2023 |access-date=2023-04-19 |url-status=live |archive-url=https://web.archive.org/web/20230420021650/https://learn.microsoft.com/en-us/visualstudio/releasenotes/vs2017-relnotes-v15.5 |archive-date= Apr 20, 2023 }}</ref>
|-
| scope="row" | 7.3<ref>{{Cite web|url=https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7-3|title=What's new in C# 7.3|website=Microsoft Docs|access-date=2018-06-23|archive-date=June 23, 2018|archive-url=https://web.archive.org/web/20180623113321/https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7-3|url-status=live}}</ref>
| [https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-7.3/ Specification proposal] {{Webarchive|url=https://web.archive.org/web/20210307081157/https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-7.3/ |date=March 7, 2021 }}
| May 2018
| {{ubl|.NET Core 2.1|.NET Core 2.2|[[.NET Framework 4.8]]}}
| [[Visual Studio 2017]] version 15.7<ref>{{Cite web|url=https://learn.microsoft.com/en-us/visualstudio/releasenotes/vs2017-relnotes-v15.7|title=Visual Studio 2017 version 15.7 Release Notes|website=Microsoft Learn|date=July 13, 2022|access-date=2023-04-19|archive-date=April 20, 2023|archive-url=https://web.archive.org/web/20230420021650/https://learn.microsoft.com/en-us/visualstudio/releasenotes/vs2017-relnotes-v15.7|url-status=live}}</ref>
|-
| scope="row" | 8.0<ref>{{Cite web|url=https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8|title=What's new in C# 8.0|website=Microsoft Docs|date=March 9, 2023|access-date=April 14, 2019|archive-date=September 6, 2020|archive-url=https://web.archive.org/web/20200906163227/https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8|url-status=live}}</ref>
| colspan="2" rowspan="6" {{no|None}}
| [https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/ Specification proposal]
| September 2019
| {{ubl|.NET Core 3.0|.NET Core 3.1}}
| [[Visual Studio 2019]] version 16.3<ref>{{Cite web|url=https://learn.microsoft.com/en-us/visualstudio/releases/2019/release-notes-v16.3|title=Visual Studio 2019 version 16.3 Release Notes|website=Microsoft Learn|date=April 11, 2023 |access-date=2023-04-19 |url-status=live |archive-url=https://web.archive.org/web/20230420021652/https://learn.microsoft.com/en-us/visualstudio/releases/2019/release-notes-v16.3 |archive-date= Apr 20, 2023 }}</ref>
|-
| scope="row" | 9.0<ref>{{Cite web|last=BillWagner|title=What's new in C# 9.0 - C# Guide|url=https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-9|access-date=2020-10-15|website=Microsoft Learn|language=en-us|archive-date=September 5, 2020|archive-url=https://web.archive.org/web/20200905125516/https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-9|url-status=live}}</ref>
| [https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-9.0/ Specification proposal]
| November 2020
| {{ubl|.NET 5.0}}
| [[Visual Studio 2019]] version 16.8<ref>{{Cite web|url=https://learn.microsoft.com/en-us/visualstudio/releases/2019/release-notes-v16.8|title=Visual Studio 2019 version 16.8 Release Notes|website=Microsoft Learn|date=April 11, 2023|access-date=2023-04-19|archive-date=April 20, 2023|archive-url=https://web.archive.org/web/20230420021651/https://learn.microsoft.com/en-us/visualstudio/releases/2019/release-notes-v16.8|url-status=live}}</ref>
|-
| scope="row" | 10.0<ref>{{Cite web|title=What's new in C# 10|url=https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-10|access-date=2021-11-10|website=Microsoft Learn|language=en-us|archive-date=February 8, 2022|archive-url=https://web.archive.org/web/20220208222424/https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-10|url-status=live}}</ref>
| [https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-10.0/ Specification proposal]
| November 2021
| {{ubl|.NET 6.0}}
| [[Visual Studio 2022]] version 17.0<ref>{{Cite web|url=https://learn.microsoft.com/en-us/visualstudio/releases/2022/release-notes-v17.0|title=Visual Studio 2022 version 17.0 Release Notes|website=Microsoft Learn|access-date=2023-04-19|archive-date=July 16, 2023|archive-url=https://web.archive.org/web/20230716094736/https://learn.microsoft.com/en-us/visualstudio/releases/2022/release-notes-v17.0|url-status=live}}</ref>
|-
| scope="row" | 11.0<ref>{{Cite web|title=What's new in C# 11|url=https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-11|access-date=2022-08-08|website=Microsoft Learn|language=en-us|archive-date=August 15, 2022|archive-url=https://web.archive.org/web/20220815142541/https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-11|url-status=live}}</ref>
| [https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-11.0/ Specification proposal]
| November 2022
| {{ubl|.NET 7.0}}
| [[Visual Studio 2022]] version 17.4<ref>{{Cite web|url=https://learn.microsoft.com/en-us/visualstudio/releases/2022/release-notes-v17.4|title=Visual Studio 2022 version 17.4 Release Notes|website=Microsoft Learn|access-date=2023-04-19|archive-date=August 6, 2023|archive-url=https://web.archive.org/web/20230806130647/https://learn.microsoft.com/en-us/visualstudio/releases/2022/release-notes-v17.4|url-status=live}}</ref>
|-
| scope="row" | 12.0<ref>{{Cite web|title=What's new in C# 12|url=https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-12|access-date=2023-06-29|website=Microsoft Learn|language=en-us|archive-date=July 20, 2023|archive-url=https://web.archive.org/web/20230720114545/https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-12|url-status=live}}</ref>
| [https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-12/ Specification proposal]
| November 2023
| {{ubl|.NET 8.0}}
| [[Visual Studio 2022]] version 17.8<ref>{{Cite web|url=https://learn.microsoft.com/en-us/visualstudio/releases/2022/release-notes-v17.8|title=Visual Studio 2022 version 17.8 Release Notes|website=Microsoft Learn|date=August 13, 2024 |access-date=2024-11-18|archive-date=October 6, 2024|archive-url=https://web.archive.org/web/20241006041528/https://learn.microsoft.com/en-us/visualstudio/releases/2022/release-notes-v17.8|url-status=live}}</ref>
|-
| scope="row" | 13.0<ref>{{Cite web|title=What's new in C# 13|url=https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-13|access-date=2024-11-18|website=Microsoft Learn|language=en-us|archive-date=November 13, 2024|archive-url=https://web.archive.org/web/20241113030010/https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-13|url-status=live}}</ref>
| [https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-13/ Specification proposal]
| November 2024
| {{ubl|.NET 9.0}}
| [[Visual Studio 2022]] version 17.12<ref>{{Cite web|url=https://learn.microsoft.com/en-us/visualstudio/releases/2022/release-notes|title=Visual Studio 2022 Release Notes|website=Microsoft Learn|date=November 12, 2024 |access-date=2024-11-18|archive-date=November 12, 2024|archive-url=https://web.archive.org/web/20241112180619/https://learn.microsoft.com/en-us/visualstudio/releases/2022/release-notes|url-status=live}}</ref>
|}
 
==Syntax==
The effect is to write the text ''Hello world!'' to the output console. Each line serves a specific purpose, as follows:
{{Main|C Sharp syntax|l1 = C# syntax}}
 
{{See also|Syntax (programming languages)}}
'''public''' '''class''' ExampleClass
The core syntax of the C# language is similar to that of other C-style languages such as C, Objective-C, C++ and Java, particularly:
 
* Semicolons are used to denote the end of a statement.
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.
* [[Curly brackets]] are used to group statements. Statements are commonly grouped into methods (functions), methods into classes, and classes into [[namespaces]].
* Variables are assigned using an [[equals sign]], but compared using [[==|two consecutive equals signs]].
* [[Square brackets]] are used with [[Array data structure|arrays]], both to declare them and to get a value at a given index in one of them.
* "class", "int" and "void" are used to define large-scale (usually main) program functions in scripts most of the time in C-style computer programming languages.
 
==Distinguishing features==
'''public''' '''static''' '''void''' Main()
{{See also|Comparison of C Sharp and Java|l1=Comparison of C# and Java}}
Some notable features of C# that distinguish it from C, C++, and Java where noted, are:
 
===Portability===
This is the entry point where the program begins execution. It could be called from other code using the syntax <code>ExampleClass.Main()</code>. (The '''public''' '''static''' '''void''' portion is a subject for a slightly more advanced discussion.)
By design, C# is the programming language that most directly reflects the underlying [[Common Language Infrastructure]]&nbsp;(CLI).{{sfn|Novák|Velvart|Granicz|Balássy|2010}} Most of its intrinsic types correspond to value-types implemented by the [[Common Language Infrastructure|CLI (Common Language Infrastructure)]] framework. However, the 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|Common Language Runtime (CLR)]], or generate [[Common Intermediate Language|Common Intermediate Language (CIL)]], or generate any other specific format. Some C# compilers can also generate machine code like traditional compilers of Objective-C, C, C++, Assembly and [[Fortran]].<ref>{{Cite web |author1=stevewhims |author2=mattwojo |date=2022-10-20 |title=Compiling Apps with .NET Native - UWP applications |url=https://learn.microsoft.com/en-us/windows/uwp/dotnet-native/ |access-date=2023-10-27 |website=learn.microsoft.com |language=en-us |archive-date=October 27, 2023 |archive-url=https://web.archive.org/web/20231027220533/https://learn.microsoft.com/en-us/windows/uwp/dotnet-native/ |url-status=live }}</ref><ref>{{Cite web |author1=LakshanF |author2=agocke |author3=Rick-Anderson |author4=gewarren |author5=IEvangelist |author6=MichalStrehovsky |author7=just-a-hriday |author8=mitchdenny |author9=am11 |author10=jkotas |author11=GitHubPang |display-authors=3 |date=2023-09-12 |title=Native AOT deployment overview - .NET |url=https://learn.microsoft.com/en-us/dotnet/core/deploying/native-aot/ |access-date=2023-10-27 |website=learn.microsoft.com |language=en-us |archive-date=November 11, 2023 |archive-url=https://web.archive.org/web/20231111093836/https://learn.microsoft.com/en-us/dotnet/core/deploying/native-aot/ |url-status=live }}</ref>
 
===Typing===
System.Console.WriteLine("Hello world!");
C# supports strongly, implicitly typed variable declarations with the keyword <code>var</code>,{{sfn|Skeet|2019}}{{rp|470}} and implicitly typed arrays with the keyword <code>new[]</code> followed by a collection initializer.{{sfn|Skeet|2019}}{{rp|80}}{{sfn|Albahari|2022}}{{rp|58}}
 
Its type system is split into two families: Value types, like the built-in numeric types and user-defined structs, which are automatically handed over as copies when used as parameters, and reference types, including arrays, instances of classes, and strings, which only hand over a pointer to the respective object. Due to their special handling of the equality operator and their [[Immutable object|immutability]], strings will nevertheless behave as if they were values, for all practical purposes. The programmer can even use them as [[Switch statement|case]] labels. Where necessary, value types will be [[Boxing (computer science)|boxed]] automatically.<ref>{{cite web|url=https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/types#81-general|title=Types/General, part of the official C# documentation|publisher=[[Microsoft]]|access-date=2024-04-06|archive-date=March 29, 2024|archive-url=https://web.archive.org/web/20240329145803/https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/types#81-general|url-status=live}}</ref>
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.
 
C# supports a strict [[Boolean data type]], <code>bool</code>. Statements that take conditions, such as <code>while</code> and <code>if</code>, require an expression of a type that evaluates to the <code>true</code> boolean value. While C++ also has a Boolean type, it can be freely converted to and from integers, and expressions such as <code>if (a)</code> require only that <code>a</code> is convertible to bool, allowing <code>a</code> 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 <code>bool</code> can prevent certain types of programming mistakes such as <code>if (a = b)</code> (use of assignment <code>=</code> instead of equality <code>==</code>).
== Standardization ==
 
C# is more [[Type safety|type safe]] than C++. The only [[implicit conversion]]s by default are those that are considered safe, such as widening of integers. This is enforced at compile-time, during [[Just-in-time compilation|JIT]], and, in some cases, at runtime. No implicit conversions occur between Booleans and integers, nor between enumeration members and integers (except for literal 0, which can be implicitly converted to any enumerated type). Any user-defined conversion must be explicitly marked as explicit or implicit, unlike C++ [[copy constructor]]s and conversion operators, which are both implicit by default.
Microsoft has submitted C# to the [[European Computer Manufacturers Association|ECMA]] for formal [[standardization]]. In December [[2001]], ECMA released ECMA-334 ''C# Language Specification''. C# became an [[ISO]] standard in 2003 (ISO/IEC 23270). There are independent implementations being worked on, including:
* [[Mono development platform|Mono]], [[Novell]]'s [[open source]] .NET implementation (originally by [[Ximian]]).
* [[dotGNU]], and [[Portable.NET]] from the [[Free Software Foundation]]
 
C# has explicit support for [[Covariance and contravariance (computer science)|covariance and contravariance]] in generic types,{{sfn|Skeet|2019}}{{rp|144}}{{sfn|Albahari|2022}}{{rp|23}} unlike C++ which has some degree of support for contravariance simply through the semantics of return types on virtual methods.
More recently, Microsoft has added support in beta releases of Visual Studio 2005 for [[Generic_programming|generics]] (similar to C++ [[template (programming)|templates]]), [[partial type]]s and some other new features. ECMA/ISO standardization of these new features has been proposed, but they are not currently part of the standard language definition.
 
[[enumerated type|Enumeration]] members are placed in their own [[Scope (programming)|scope]].
==Politics==
 
The C# language does not allow for global variables or functions. All methods and members must be declared within classes. Static members of public classes can substitute for global variables and functions.
Many of Microsoft's products and initiatives generate political attention, and C# is no exception. Owing to C#'s close relationship with a commercial institution, political discussions continue regarding the legitimacy of C# standardization, its Java similarities, its future as a general-purpose language, and other issues. Some security experts express skepticism as to the efficacy of the CLR's security mechanisms, and criticise their complexity. At the same time, the language is praised for its clear and programmer-friendly grammar, in addition to dramatic drops in application development time (as opposed to C++).
 
Local variables cannot [[Variable shadowing|shadow]] variables of the enclosing block, unlike C and C++, but may shadow type-level names.
Unlike proprietary languages such as Visual Basic or Java, Microsoft chose to open up C# to the standardization process. However, Microsoft is still a primary force driving changes and innovation in the language. Additionally, 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. Microsoft takes an active role in marketing the language as part of its overall business strategies.
<!--NOTE TO EDITORS: Classes do NOT *NEED* to go in a Namespace. Check the spec or try it out yourself before stating otherwise.-->
 
===Metaprogramming===
== Language name ==
[[Metaprogramming]] can be achieved in several ways:
The name "C#" may have been chosen by Microsoft to imply progression from the C++ language, with the # symbol resembling two + symbols merged together, or four + symbols arranged in a square.
 
* [[Reflective programming|Reflection]] is supported through .NET APIs, which enable scenarios such as type metadata inspection and dynamic method invocation.
[[Image:C sharp.gif|thumb|100px|right|C Sharp]]
* Expression trees<ref>{{Cite web|last=BillWagner|title=Expression Trees (C#)|url=https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/expression-trees/|access-date=2021-05-14|website=Microsoft Learn|language=en-us|archive-date=May 15, 2021|archive-url=https://web.archive.org/web/20210515000042/https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/expression-trees/|url-status=live}}</ref> represent code as an [[abstract syntax tree]], where each node is an expression that can be inspected or executed. This enables dynamic modification of executable code at runtime. Expression trees introduce some [[homoiconicity]] to the language.
According to Microsoft [http://msdn.microsoft.com/vcsharp/productinfo/faq/default.aspx], the symbol in the name "C#" is ♯, the musical sharp symbol (see graphic at right if the symbol is not visible). Therefore, the proper representation is "C♯". It follows then that the name of the language is pronounced "''see-sharp''", like the [[Note|musical note]].
* [[Attribute (computing)|Attributes]], in C# parlance, are [[metadata]] that can be attached to types, members, or entire [[Assembly (programming)|assemblies]], equivalent to [[Java annotation|annotations in Java]]. Attributes are accessible both to the compiler and to code through reflection, allowing them to adjust their behaviour.<ref>{{Cite web|url=https://learn.microsoft.com/en-us/dotnet/api/system.attribute|title=Attribute Class}}</ref> Many of the native attributes duplicate the functionality of GCC's and VisualC++'s platform-dependent preprocessor directives.{{Citation needed|date=March 2022}}
* <code>System.Reflection.Emit</code> namespace,<ref>{{Cite web |last=dotnet-bot |title=System.Reflection.Emit Namespace |url=https://learn.microsoft.com/en-us/dotnet/api/system.reflection.emit?view=net-8.0 |access-date=2023-04-28 |website=learn.microsoft.com |language=en-us |archive-date=April 28, 2023 |archive-url=https://web.archive.org/web/20230428191740/https://learn.microsoft.com/en-us/dotnet/api/system.reflection.emit?view=net-8.0 |url-status=live }}</ref> which contains classes that emit metadata and [[Common Intermediate Language|CIL]] (types, assemblies, etc.) at [[Runtime system|runtime]].
* [[Roslyn (compiler)|The .NET Compiler Platform (Roslyn)]] provides API access to language compilation services, allowing for the compilation of C# code from within .NET applications. It exposes APIs for syntactic ([[Lexical analysis|lexical]]) analysis of code, [[Semantic analysis (compilers)|semantic analysis]], dynamic compilation to CIL, and code emission.<ref>{{Cite web |last=McAllister |first=Neil |date=2011-10-20 |title=Microsoft's Roslyn: Reinventing the compiler as we know it |url=https://www.infoworld.com/article/2621132/microsoft-s-roslyn--reinventing-the-compiler-as-we-know-it.html |access-date=2022-03-05 |website=InfoWorld |language=en |archive-date=March 5, 2022 |archive-url=https://web.archive.org/web/20220305160503/https://www.infoworld.com/article/2621132/microsoft-s-roslyn--reinventing-the-compiler-as-we-know-it.html |url-status=live }}</ref>
* Source generators,<ref>{{Cite web|date=2020-04-29|title=Introducing C# Source Generators|url=https://devblogs.microsoft.com/dotnet/introducing-c-source-generators/|access-date=2021-05-14|website=.NET Blog|language=en-US|archive-date=May 7, 2021|archive-url=https://web.archive.org/web/20210507115127/https://devblogs.microsoft.com/dotnet/introducing-c-source-generators/|url-status=live}}</ref> a feature of the Roslyn C# compiler, enable compile time metaprogramming. During the compilation process, developers can inspect the code being compiled with the compiler's [[API]] and pass additional generated C# source code to be compiled.
 
===Methods and functions===
However, according to the ECMA-334 C# Language Specification, section 6, ''Acronyms and abbreviations'' [http://www.ecma-international.org/publications/standards/Ecma-334.htm] 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".
A ''method'' in C# is a member of a class that can be invoked as a function (a sequence of instructions), rather than the mere value-holding capability of a ''field'' (i.e. [[Class variable|class]] or [[instance variable]]).<ref>{{cite web|url=https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/classes#155-fields|title=Classes/fields, part of the official C# documentation|date=February 7, 2024 }}</ref> As in other syntactically similar languages, such as [[C++]] and [[ANSI C]], the signature of a method is a declaration comprising in order: any optional accessibility keywords (such as <code>private</code>), the explicit specification of its return type (such as <code>int</code>, or the keyword <code>void</code> if no value is returned), the name of the method, and finally, a parenthesized sequence of comma-separated parameter specifications, each consisting of a parameter's type, its formal name and optionally, a default value to be used whenever none is provided. Different from most other languages, [[Evaluation strategy|call-by-reference]] parameters have to be marked both at the function definition and at the calling site, and the programmer can choose between <code>ref</code> and <code>out</code>, the latter allowing handing over an uninitialized variable which will have a definite value on return.<ref>{{cite web|url=https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/out|title=out (C# Reference)|date=March 30, 2024 }}</ref> Additionally, the programmer can specify a [[Variadic function|variable-sized argument list]] by applying the <code>params</code> keyword to the last parameter.<ref>{{cite web|url=https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/method-parameters#params-modifier|title=Method parameters/params modifier, part of the official C# documentation|date=May 21, 2024 }}</ref> Certain specific kinds of methods, such as those that simply get or set a field's value by returning or assigning it, do not require an explicitly stated full signature, but in the general case, the definition of a class includes the full signature declaration of its methods.<ref name="properties">{{cite web|url=https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/classes#157-properties|title=Classes/properties, part of the official C# documentation|date=February 7, 2024 }}</ref>
 
Like C++, and unlike Java, C# programmers must use the scope modifier keyword <code>virtual</code> to allow methods to be [[method overriding|overridden]] by subclasses. Unlike C++, the programmer must explicitly specify the keyword <code>override</code> when doing so.<ref>{{cite web|title=virtual (C# Reference)|url=https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/virtual|website=Microsoft Learn|date=September 15, 2021|language=en-us|access-date=April 4, 2018|archive-date=August 30, 2018|archive-url=https://web.archive.org/web/20180830073741/https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/virtual|url-status=live}}</ref> This is supposed to avoid confusion between overriding and newly overloading a function (i.e. hiding the former implementation). To do the latter, the programmer has to specify the <code>new</code> keyword.<ref>{{cite web|url=https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/new-modifier|title='''new''' modifier, part of the official C# documentation|date=April 12, 2023 }}</ref> The keyword <code>sealed</code> can be used to disallow further overrides for individual methods or whole classes.<ref>{{cite web|url=https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/abstract-and-sealed-classes-and-class-members |title=Abstract and Sealed Classes and Class Members - C# |date=October 27, 2021 }}</ref>
Due to technical limitations of display (fonts, browsers, etc.) and the fact that ♯ sharp symbol is not present on the standard keyboard, the # hash symbol is often used. Unfortunately, the hash symbol is often used in books as well [http://www.microsoft.com/MSPress/books/imgt/5029.gif], presumably leading to more confusion regarding the name of the language. Users have been known to call the language "''see-pound''" (in the US the #-key on telephones is pronounced as the "''pound''"-key) or "''see-hash''". Also in the US the # symbol is also occasionally referred to as the "''gate''" symbol on a telephone, leading to a pronunciation of the language as "''see-gate''", which could be confused with the brand name of hard-drive manufacturer, [[Seagate]].
 
''Extension methods'' in C# allow programmers to use static methods as if they were methods from a class's method table, allowing programmers to virtually add instance methods to a class that they feel should exist on that kind of objects (and instances of the respective derived classes).{{sfn|Skeet|2019}}{{rp|103–105}}{{sfn|Albahari|2022}}{{rp|202–203}}
Another name for the # symbol is "''[[octothorpe]]''", which when combined with a hard C sound, results in the pronunciation "''cock-toe-thorp''". This form, spoken emphasising the first syllable, is occasionally used as an [[expletive]] by programmers.
 
The type <code>dynamic</code> allows for run-time method binding, allowing for JavaScript-like method calls and run-time [[object composition]].{{sfn|Skeet|2019}}{{rp|114–118}}
The "sharp" suffix has been emulated by a number of other .NET languages that are variants of existing languages, including [[J Sharp|J#]] (Microsoft's implementation of Java, [[A Sharp (.NET)|A#]] (from [[Ada programming language|Ada]]), [[F Sharp|F#]] (presumably from [[System F]], the type system used by the [[ML programming language|ML]] family), and Gtk# (a .NET wrapper for [[GIMP Toolkit|GTK+]]).
 
C# has support for strongly-typed [[function pointer]]s via the keyword <code>delegate</code>. Like the [[Qt (software)|Qt]] framework's [[pseudo]]-C++ ''signal'' and ''slot'', C# has semantics specifically surrounding publish-subscribe style events, though C# uses delegates to do so. Unlike fields, <code>event</code> variables can be part of an interface, because they technically consist of two default functions to add and remove to-be-called delegates.
== See also ==
{{Wikibookspar|Programming|C_sharp}}
*[[Mono development platform|Mono]], an open source implementation of C# and .NET
*[[F Sharp programming language|F# programming language]]
*[[Cω|C&omega; programming language]], extension to C#
*[[D programming language]]
*[[Spec_sharp|Spec♯]]
*[[Sing_sharp|Sing♯]]
*[[Nemerle|Nemerle programming language]]
*[[Boo programming language]], a cross between C# and [[Python programming language|Python]]
*[[IronPython]], a [[Microsoft]]-supported, .NET-compliant version of [[Python programming language|Python]]
*[[Polyphonic C sharp|Polyphonic C#]]
*[[Comparison of C Sharp to Java|Comparison of C# to Java]]
*[[Common Language Runtime]]
*[[Anders Hejlsberg]]
*[[C_Plus_Plus_CLI|C++/CLI]]
 
C# offers Java-like <code>synchronized</code> method calls, via the attribute <code>[MethodImpl(MethodImplOptions.Synchronized)]</code>, and has support for [[Mutual exclusion|mutually-exclusive locks]] via the keyword <code>lock</code>.
== External links ==
*[http://msdn.microsoft.com/vcsharp/team/language/default.aspx C# Language (MSDN)]
*[http://msdn.microsoft.com/library/default.asp?url=/library/en-us/csspec/html/CSharpSpecStart.asp C# Specification]
*[http://www.ecma-international.org/publications/files/ecma-st/ECMA-334.pdf ECMA-334 C# Language Specification (.pdf)]
*[http://msdn.microsoft.com/vcsharp/ Microsoft Visual C# .NET]
*[http://www.computer-books.us/csharp.php Computer-Books.us] - A collection of C# books available for free download.
*[http://www.csharpfriends.com C# Community Site]
*[http://www.mono-project.com/using/mcs.html MCS: The Mono C# compiler]
*[http://www.southern-storm.com.au/portable_net.html Portable.NET]
*[http://www.borland.com/csharpbuilder/ Borland's C# Builder for the Microsoft® .NET Framework]
*[http://www.icsharpcode.net SharpDevelop: Open Source C# IDE]
*news://msnews.microsoft.com/microsoft.public.dotnet.languages.csharp
 
===Properties===
{{Major programming languages small}}
C# supports classes with [[property (programming)|properties]]. The properties can be simple accessor functions with a backing field, or implement arbitrary getter and setter functions. A property is read-only if there's no setter. Like with fields, there can be class and instance properties. The underlying methods can be <code>virtual</code> or [[Abstract method#Abstract methods|<code>abstract</code>]] like any other method.<ref name="properties" />
 
Since C# 3.0 the [[syntactic sugar]] of auto-implemented properties is available,<ref name="auto-implemented property">{{cite web|url=https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/auto-implemented-properties|title=Auto-Implemented Properties (C# Programming Guide)|access-date=September 12, 2020|archive-date=October 29, 2020|archive-url=https://web.archive.org/web/20201029204026/https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/auto-implemented-properties|url-status=live}}</ref> where the [[Mutator method|accessor (getter) and mutator (setter)]] encapsulate operations on a single field of a class.
[[Category:Programming languages|C#]]
 
[[Category:Class-based programming languages]]
===Namespaces===
A C# <code>namespace</code> provides the same level of code isolation as a Java <code>package</code> or a C++ {{C++|namespace}}, with rules and features very similar to a <code>package</code>. Namespaces can be imported with the "using" syntax.<ref>{{Cite web|url=https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-directive|title=using directive - C# Reference|website=Microsoft Docs|language=en-us|access-date=2019-04-14|archive-date=April 14, 2019|archive-url=https://web.archive.org/web/20190414022555/https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-directive|url-status=live}}</ref>
 
===Memory access===
In C#, memory address pointers can only be used within blocks specifically marked as ''unsafe'',<ref>{{Cite web|last=BillWagner|title=Unsafe code, pointers to data, and function pointers|url=https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/unsafe-code|access-date=2021-06-20|website=Microsoft Learn|language=en-us|archive-date=July 4, 2021|archive-url=https://web.archive.org/web/20210704170809/https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/unsafe-code|url-status=live}}</ref> and programs with unsafe code need appropriate permissions to run. Most object access is done through safe object references, which always either point to a "live" object or have the well-defined [[Nullable type|null]] value; it is impossible to obtain a reference to a "dead" object (one that has been garbage collected), or to an arbitrary block of memory. An unsafe pointer can point to an instance of an unmanaged value type that does not contain any references to objects subject to garbage collections such as class instances, arrays or strings. Code that is not marked as unsafe can still store and manipulate pointers through the <code>System.IntPtr</code> type, but it cannot dereference them.
 
Managed memory cannot be explicitly freed; instead, it is automatically garbage collected. Garbage collection addresses the problem of [[memory leak]]s by freeing the programmer of responsibility for releasing memory that is no longer needed in most cases. Code that retains references to objects longer than is required can still experience higher memory usage than necessary, however once the final reference to an object is released the memory is available for garbage collection.
 
===Exceptions===
A range of standard exceptions are available to programmers. Methods in standard libraries regularly throw system exceptions in some circumstances and the range of exceptions thrown is normally documented. Custom exception classes can be defined for classes allowing handling to be put in place for particular circumstances as needed.<ref>{{cite web|url=https://docs.microsoft.com/en-us/dotnet/standard/exceptions/how-to-create-user-defined-exceptions|title=How to create user-defined exceptions|access-date=September 12, 2020|archive-date=January 26, 2021|archive-url=https://web.archive.org/web/20210126131828/https://docs.microsoft.com/en-us/dotnet/standard/exceptions/how-to-create-user-defined-exceptions|url-status=live}}</ref>
 
The syntax for handling exceptions is the following:<syntaxhighlight lang="c#">try
{
// something
}
catch (Exception ex)
{
// if error do this
}
finally
{
// always executes, regardless of error occurrence
}</syntaxhighlight>Most of the time people call this a "try-catch" code block, because of the "try" and "catch" functions being used and accessible on all C# versions.<syntaxhighlight lang="c#" line="1">
try
{
// something here
}
catch (Exception ex)
{
// example
return 0;
}
finally
{
return 1;
}
</syntaxhighlight>Depending on your plans, the "finally" part can be left out. If inspecting the error details is not required, the <code>(Exception ex)</code> parameter can be omitted as well. Also, there can be several "catch" parts handling different kinds of exceptions.<ref>{{cite web |title=Exception-handling statements, part of the official C# documentation |url=https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/exception-handling-statements |access-date=2024-06-26 |website=Microsoft Learn|date=April 22, 2023 }}</ref>
 
[[Checked exceptions]] are not present in C# (in contrast to Java). This has been a conscious decision based on the issues of scalability and version management.<ref>{{cite web
| url = http://www.artima.com/intv/handcuffs.html
| title = The Trouble with Checked Exceptions
| first1 = Bill
| last1 = Venners
| first2 = Bruce
| last2 = Eckel
| date = August 18, 2003
| access-date = March 30, 2010
| archive-date = February 18, 2015
| archive-url = https://web.archive.org/web/20150218200616/http://www.artima.com/intv/handcuffs.html
| url-status = live
}}</ref>
 
===Polymorphism===
Unlike [[C++]], C# does not support [[multiple inheritance]], although a class can implement any number of "[[Protocol (object-oriented programming)|interfaces]]" (fully abstract classes). This was a design decision by the language's lead architect to avoid complications and to simplify architectural requirements throughout [[Common Language Infrastructure|CLI]].
 
When implementing multiple interfaces that contain a method with the same name and taking parameters of the same types in the same order (i.e. the same [[Type signature|signature]]), similar to [[Java (programming language)|Java]], C# allows both a single method to cover all interfaces and if necessary specific methods for each interface.
 
C# also offers [[function overloading]] (a.k.a. [[Ad hoc polymorphism|ad-hoc-polymorphism]]), i.e. methods with the same name, but distinguishable signatures.<ref>{{cite web|url=https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/expressions#1264-overload-resolution|title=Expressions/Overload resolution, part of the official C# documentation|website=Microsoft Learn|date=February 7, 2024 |access-date=2024-04-07}}</ref> Unlike Java, C# additionally supports [[operator overloading]].<ref>{{Cite web|last=BillWagner|title=Operator overloading - C# reference|url=https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/operator-overloading|access-date=2021-06-20|website=Microsoft Learn|language=en-us|archive-date=June 24, 2021|archive-url=https://web.archive.org/web/20210624202405/https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/operator-overloading|url-status=live}}</ref>
 
Since version 2.0, C# offers [[parametric polymorphism]], i.e. classes with arbitrary or constrained type parameters, e.g. <code>List<T></code>, a variable-sized array which only can contain elements of type <code>T</code>. There are certain kinds of constraints the programmer can specify for the type parameters: Has to be type X ([[Liskov substitution principle|or one derived from it]]), has to implement a certain interface, has to be a reference type, has to be a value type, has to implement a public parameterless [[Constructor (object-oriented programming)|constructor]]. Most of them can be combined, and any number of interfaces can be specified.<ref>{{cite web|url=https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/types#841-general|title=Types/Constructed Types, part of the official C# documentation|website=Microsoft Learn|access-date=2024-04-07}}</ref><ref>{{cite web|url=https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/classes#1525-type-parameter-constraints|title=Classes/Type Parameter constraints, part of the official C# documentation|website=Microsoft Learn|date=February 7, 2024 |access-date=2024-04-07}}</ref>
 
===Language Integrated Query (LINQ)===
C# has the ability to utilize [[Language Integrated Query|LINQ]] through the .NET Framework. A developer can query a variety of data sources, provided the <code>IEnumerable&lt;T&gt;</code> interface is implemented on the object. This includes [[XML]] documents, an [[ADO.NET]] dataset, and [[SQL]] databases.<ref>{{cite journal |last1=Zhang |first1=Xue Dong |last2=Teng |first2=Zi Mu |last3=Zhao |first3=Dong Wang |title=Research of the Database Access Technology Under.NET Framework |journal=Applied Mechanics and Materials |date=September 2014 |volume=644-650 |pages=3077–3080 |id={{ProQuest|1565579768}} |doi=10.4028/www.scientific.net/AMM.644-650.3077 |s2cid=62201466 }}</ref>
 
Using [[Language Integrated Query|LINQ]] in C# brings advantages like [[IntelliSense]] support, strong filtering capabilities, type safety with compile error checking ability, and consistency for querying data over a variety of sources.<ref>{{cite magazine |last1=Otey |first1=Michael |date=February 2006 |title=LINQ to the Future |magazine=SQL Server Magazine |volume=8 |issue=2 |pages=17–21 |id={{ProQuest|214859896}} }}</ref> There are several different language structures that can be utilized with C# and LINQ and they are query expressions, lambda expressions, anonymous types, implicitly typed variables, extension methods, and object initializers.<ref>{{cite magazine |last1=Sheldon |first1=William |date=November 2010 |title=New Features in LINQ |magazine=SQL Server Magazine |volume=12 |issue=11 |pages=37–40 |id={{ProQuest|770609095}} }}</ref>
 
LINQ has two syntaxes: query syntax and method syntax. However, the compiler always converts the query syntax to method syntax at compile time.<ref>{{Cite web |last=BillWagner |date=2021-09-15 |title=Query Syntax and Method Syntax in LINQ (C#) |url=https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/query-syntax-and-method-syntax-in-linq |access-date=2023-05-23 |website=learn.microsoft.com |language=en-us |archive-date=May 23, 2023 |archive-url=https://web.archive.org/web/20230523023209/https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/query-syntax-and-method-syntax-in-linq |url-status=live }}</ref>
 
<syntaxhighlight lang="csharp">
using System.Linq;
 
var numbers = new int[] { 5, 10, 8, 3, 6, 12 };
 
// Query syntax (SELECT num FROM numbers WHERE num % 2 = 0 ORDER BY num)
var numQuery1 =
from num in numbers
where num % 2 == 0
orderby num
select num;
 
// Method syntax
var numQuery2 =
numbers
.Where(num => num % 2 == 0)
.OrderBy(n => n);
</syntaxhighlight>
 
===Functional programming===
Though primarily an imperative language, C# always adds functional features over time,<ref>{{Cite web |last=erikdietrich |title=The history of C# - C# Guide |url=https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-version-history |access-date=2023-04-28 |website=learn.microsoft.com |date=March 9, 2023 |language=en-us |archive-date=April 28, 2023 |archive-url=https://web.archive.org/web/20230428185411/https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-version-history |url-status=live }}</ref><ref>{{Citation |title=The functional journey of C# - Mads Torgersen - NDC Copenhagen 2022 | date=August 17, 2022 |url=https://www.youtube.com/watch?v=CLKZ7ZgVido |access-date=2023-05-15 |language=en |archive-date=May 15, 2023 |archive-url=https://web.archive.org/web/20230515042003/https://www.youtube.com/watch?v=CLKZ7ZgVido |url-status=live }}</ref> for example:
 
* [[First-class function|Functions as first-class citizen]] – C# 1.0 delegates<ref>{{Cite web |title=The Beauty of Closures |url=https://csharpindepth.com/Articles/Closures |access-date=2023-04-28 |website=csharpindepth.com |archive-date=May 19, 2023 |archive-url=https://web.archive.org/web/20230519162434/https://csharpindepth.com/articles/Closures |url-status=live }}</ref>
* [[Higher-order function]]s – C# 1.0 together with delegates
* [[Anonymous function]]s – C# 2 anonymous delegates and C# 3 lambdas expressions<ref name="BillWagner">{{Cite web |last=BillWagner |title=Anonymous functions - C# Programming Guide |url=https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/anonymous-functions |access-date=2021-05-15 |website=Microsoft Learn |language=en-us |archive-date=April 15, 2021 |archive-url=https://web.archive.org/web/20210415001944/https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/anonymous-functions |url-status=live }}</ref>
* [[Closure (computer programming)|Closures]] – C# 2 together with anonymous delegates and C# 3 together with lambdas expressions<ref name="BillWagner" />
* [[Type inference]] – C# 3 with implicitly typed local variables {{C sharp|var}} and C# 9 target-typed new expressions {{C sharp|new()}}
* [[List comprehension]] – C# 3 LINQ
* [[Tuple]]s – [[.NET Framework]] 4.0 but it becomes popular when C# 7.0 introduced a new tuple type with language support<ref name=":0">{{Cite web |title=What's New in C# 7.0 |url=https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7 |access-date=2019-04-14 |website=Microsoft Docs |language=en-us |archive-date=August 6, 2020 |archive-url=https://web.archive.org/web/20200806121012/https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7 |url-status=live }}</ref>
* [[Nested function]]s – C# 7.0<ref name=":0" />
* [[Pattern matching]] – C# 7.0<ref name=":0" />
* [[Immutable object|Immutability]] – C# 7.2 readonly struct C# 9 record types<ref>{{Cite web |date=2020-11-10 |title=C# 9.0 on the record |url=https://devblogs.microsoft.com/dotnet/c-9-0-on-the-record/ |access-date=2021-05-15 |website=.NET Blog |language=en-US |archive-date=May 15, 2021 |archive-url=https://web.archive.org/web/20210515081243/https://devblogs.microsoft.com/dotnet/c-9-0-on-the-record/ |url-status=live }}</ref> and Init only setters<ref>{{Cite web |last=BillWagner |date=2022-06-30 |title=init keyword - C# Reference |url=https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/init |access-date=2023-05-19 |website=learn.microsoft.com |language=en-us |archive-date=May 19, 2023 |archive-url=https://web.archive.org/web/20230519193119/https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/init |url-status=live }}</ref>
* [[Type class]]es – C# 12 roles/extensions (in development<ref>{{Citation |title=The .NET Compiler Platform |date=2023-04-28 |url=https://github.com/dotnet/roslyn/blob/ce2b2c7d31eb985d9a75bf967eb43eaa15ab7c68/docs/Language%20Feature%20Status.md |access-date=2023-04-28 |publisher=.NET Platform |archive-date=April 28, 2023 |archive-url=https://web.archive.org/web/20230428185411/https://github.com/dotnet/roslyn/blob/ce2b2c7d31eb985d9a75bf967eb43eaa15ab7c68/docs/Language%20Feature%20Status.md |url-status=live }}</ref>)
 
==Common type system==
C# has a ''unified type system''. This unified type system is called [[Common Type System]] (CTS).{{sfn|Archer|2001}}{{rp|loc=Part 2, Chapter 4: The Type System}}
 
A unified type system implies that all types, including primitives such as integers, are subclasses of the {{C sharp|System.Object}} class. For example, every type inherits a {{C sharp|ToString()}} method.
 
===Categories of data types===
CTS separates data types into two categories:{{sfn|Archer|2001}}
 
# Reference types
# Value types
 
Instances of value types neither have referential identity nor referential comparison semantics. Equality and inequality comparisons for value types compare the actual data values within the instances, unless the corresponding operators are overloaded. Value types are derived from {{C sharp|System.ValueType}}, always have a default value, and can always be created and copied. Some other limitations on value types are that they cannot derive from each other (but can implement interfaces) and cannot have an explicit default (parameterless) constructor because they already have an implicit one which initializes all contained data to the type-dependent default value (0, null, or alike). Examples of value types are all primitive types, such as {{C sharp|int}} (a signed 32-bit integer), {{C sharp|float}} (a 32-bit IEEE floating-point number), {{C sharp|char}} (a 16-bit Unicode code unit), <code>decimal</code> (fixed-point numbers useful for handling currency amounts), and {{C sharp|System.DateTime}} (identifies a specific point in time with nanosecond precision). Other examples are {{C sharp|enum}} (enumerations) and {{C sharp|struct}} (user defined structures).
 
In contrast, reference types have the notion of referential identity, meaning that each instance of a reference type is inherently distinct from every other instance, even if the data within both instances is the same. This is reflected in default equality and inequality comparisons for reference types, which test for referential rather than structural equality, unless the corresponding operators are overloaded (such as the case for {{C sharp|System.String}}). Some operations are not always possible, such as creating an instance of a reference type, copying an existing instance, or performing a value comparison on two existing instances. Nevertheless, specific reference types can provide such services by exposing a public constructor or implementing a corresponding interface (such as {{C sharp|ICloneable}} or {{C sharp|IComparable}}). Examples of reference types are {{C sharp|object}} (the ultimate base class for all other C# classes), {{C sharp|System.String}} (a string of Unicode characters), and {{C sharp|System.Array}} (a base class for all C# arrays).
 
Both type categories are extensible with user-defined types.
 
===Boxing and unboxing===
''Boxing'' is the operation of converting a value-type object into a value of a corresponding reference type.{{sfn|Archer|2001}} 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.{{sfn|Archer|2001}} Unboxing in C# requires an explicit [[Type conversion|type cast]]. A boxed object of type T can only be unboxed to a T (or a nullable T).<ref>{{cite web |last=Lippert |first=Eric |url=http://blogs.msdn.com/b/ericlippert/archive/2009/03/19/representation-and-identity.aspx |title=Representation and Identity |work=Fabulous Adventures In Coding |publisher=Blogs.msdn.com |date=March 19, 2009 |access-date=October 4, 2012 |archive-date=July 12, 2011 |archive-url=https://web.archive.org/web/20110712160124/http://blogs.msdn.com/b/ericlippert/archive/2009/03/19/representation-and-identity.aspx |url-status=live }}</ref>
 
Example:
<syntaxhighlight lang="CSharp">
int foo = 42; // Value type.
object bar = foo; // foo is boxed to bar.
int foo2 = (int)bar; // Unboxed back to value type.
</syntaxhighlight>
 
==Libraries==
The C# specification details a minimum set of types and class libraries that the compiler expects to have available. 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)''.
 
In addition to the standard CLI specifications, there are many commercial and community class libraries that build on top of the .NET framework libraries to provide additional functionality.<ref>{{Cite web|url=https://docs.microsoft.com/en-us/dotnet/standard/framework-libraries|title=Framework Libraries|website=Microsoft Learn|date=April 19, 2023|access-date=July 14, 2019|archive-date=July 14, 2019|archive-url=https://web.archive.org/web/20190714090806/https://docs.microsoft.com/en-us/dotnet/standard/framework-libraries|url-status=live}}</ref>
 
C# can make calls to any library included in the [[List of .NET libraries and frameworks]].
 
==Examples==
 
===Hello World===
The following is a very simple C# program, a version of the classic "[["Hello, World!" program|Hello world]]" example using the [https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/program-structure/top-level-statements top-level statements] feature introduced in C# 9:<ref>{{Cite web|last=BillWagner|title=What's new in C# 9.0 - C# Guide|url=https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-9|access-date=2021-05-14|website=Microsoft Learn|language=en-us|archive-date=September 5, 2020|archive-url=https://web.archive.org/web/20200905125516/https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-9|url-status=live}}</ref>
 
<syntaxhighlight lang="csharp">
System.Console.WriteLine("Hello, world!");
</syntaxhighlight>
 
For code written as C# 8 or lower, the entry point logic of a program must be written in a Main method inside a type:
 
<syntaxhighlight lang="csharp">
using System;
 
class Program
{
static void Main()
{
Console.WriteLine("Hello, world!");
}
}
</syntaxhighlight>
 
This code will display this text in the console window:
 
Hello, world!
 
Each line has a purpose:
 
<syntaxhighlight lang="CSharp">
using System;
</syntaxhighlight>
 
The above line imports all types in the <code>System</code> namespace. For example, the <code>Console</code> class used later in the source code is defined in the <code>System</code> namespace, meaning it can be used without supplying the full name of the type (which includes the namespace).
 
<syntaxhighlight lang="csharp">
// A version of the classic "Hello World" program
</syntaxhighlight>This line is a comment; it describes and documents the code for the programmer(s).<syntaxhighlight lang="CSharp">
class Program
</syntaxhighlight>
 
Above is a [[Class (computer programming)|class]] definition for the {{C sharp|Program}} class. Everything that follows between the pair of braces describes that class.<syntaxhighlight lang="csharp">
{
...
}
</syntaxhighlight>The curly brackets demarcate the boundaries of a code block. In this first instance, they are marking the start and end of the {{C sharp|Program}} class.<syntaxhighlight lang="csharp">
static void Main()
</syntaxhighlight>
 
This declares the class member method where the program begins execution. The .NET runtime calls the {{C sharp|Main}} method. Unlike in [[Java (programming language)|Java]], the {{C sharp|Main}} method does not need the {{C sharp|public}} keyword, which tells the compiler that the method can be called from anywhere by any class.<ref>{{Cite web|last=BillWagner|title=Main() and command-line arguments|url=https://docs.microsoft.com/en-us/dotnet/csharp/fundamentals/program-structure/main-command-line|access-date=2021-08-05|website=Microsoft Learn|language=en-us|archive-date=August 5, 2021|archive-url=https://web.archive.org/web/20210805164526/https://docs.microsoft.com/en-us/dotnet/csharp/fundamentals/program-structure/main-command-line|url-status=live}}</ref> Writing {{C sharp|static void Main(string[] args)}} is equivalent to writing {{C sharp|private static void Main(string[] args)}}. The [[Method (computer programming)#Static methods|static keyword]] makes the method accessible without an instance of {{C sharp|Program}}. Each console application's {{C sharp|Main}} entry point must be declared {{C sharp|static}} otherwise the program would require an instance of {{C sharp|Program}}, but any instance would require a program. To avoid that irresolvable [[circular dependency]], C# compilers processing [[console application]]s (like that above) report an error if there is no {{C sharp|static Main}} method. The {{C sharp|void}} keyword declares that {{C sharp|Main}} has no [[return value]]. (Note, however, that short programs can be written using [https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/program-structure/top-level-statements Top Level Statements] introduced in C# 9, as mentioned earlier.)
 
<syntaxhighlight lang="CSharp">
Console.WriteLine("Hello, world!");
</syntaxhighlight>
 
This line writes the output. {{C sharp|Console}} is a static class in the {{C sharp|System}} namespace. It provides an interface to the standard [[input/output]], and error streams for console applications. The program calls the {{C sharp|Console}} method {{C sharp|WriteLine}}, which displays on the console a line with the argument, the string {{C sharp|"Hello, world!"}}.
 
===Generics===
{{Further|Generic programming}}
With .NET 2.0 and C# 2.0, the community got more flexible collections than those in .NET 1.x. In the absence of generics, developers had to use collections such as ArrayList to store elements as objects of unspecified kind, which incurred performance overhead when boxing/unboxing/type-checking the contained items.
 
Generics introduced a massive new feature in .NET that allowed developers to create type-safe data structures. This shift is particularly important in the context of converting legacy systems, where updating to generics can significantly enhance performance and maintainability by replacing outdated data structures with more efficient, type-safe alternatives.<ref>{{cite web| url=https://wirefuture.com/post/unlocking-the-power-of-c-generics-a-comprehensive-guide|title=Unlocking the Power of C# Generics: A Comprehensive Guide|date=Apr 24, 2024}}</ref>
 
'''Example'''
<syntaxhighlight lang="csharp">
public class DataStore<T>
{
private T[] items = new T[10];
private int count = 0;
 
public void Add(T item)
{
items[count++] = item;
}
 
public T Get(int index)
{
return items[index];
}
}
</syntaxhighlight>
 
==Standardization and licensing==
In August 2001, [[Microsoft]], [[Hewlett-Packard]] and [[Intel]] co-sponsored the submission of specifications for C# as well as the [[Common Language Infrastructure]] (CLI) to the standards organization [[Ecma International]]. In December 2001, ECMA released ECMA-334 ''C# Language Specification''. C# became an [[International Organization for Standardization|ISO]]/[[International Electrotechnical Commission|IEC]] standard in 2003 (ISO/IEC 23270:2003 - ''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 [[Generic programming|generics]] (somewhat similar to C++ [[template (programming)|templates]]). In July 2005, ECMA submitted to ISO/IEC JTC 1/SC 22, via the latter's Fast-Track process, the standards and related TRs. This process usually takes 6–9 months.
 
The C# language definition and the CLI are standardized under ISO/IEC and [[Ecma]] standards that provide [[Reasonable and Non Discriminatory Licensing|reasonable and non-discriminatory licensing]] protection from patent claims.
 
Microsoft initially agreed not to sue open-source developers for violating patents in non-profit projects for the part of the framework that is covered by the [[Open Specification Promise]].<ref>{{cite web| url = https://msdn.microsoft.com/en-us/openspecifications/dn646765| title = Patent Pledge for Open Source Developers| date = March 16, 2023| access-date = October 28, 2017| archive-date = December 7, 2017| archive-url = https://web.archive.org/web/20171207123732/https://msdn.microsoft.com/en-us/openspecifications/dn646765| url-status = live}}</ref> Microsoft has also agreed not to enforce patents relating to [[Novell]] products against Novell's paying customers<ref>{{cite web
|url = http://www.microsoft.com/interop/msnovellcollab/patent_agreement.mspx
|title = Patent Cooperation Agreement - Microsoft & Novell Interoperability Collaboration
|date = November 2, 2006
|publisher = [[Microsoft]]
|access-date = July 5, 2009
|quote = Microsoft, on behalf of itself and its Subsidiaries (collectively "Microsoft"), hereby covenants not to sue Novell's Customers and Novell's Subsidiaries' Customers for infringement under Covered Patents of Microsoft on account of such a Customer's use of specific copies of a Covered Product as distributed by Novell or its Subsidiaries (collectively "Novell") for which Novell has received Revenue (directly or indirectly) for such specific copies; provided the foregoing covenant is limited to use by such Customer (i) of such specific copies that are authorized by Novell in consideration for such Revenue, and (ii) within the scope authorized by Novell in consideration for such Revenue.
|archive-url = https://web.archive.org/web/20090517140252/http://www.microsoft.com/interop/msnovellcollab/patent_agreement.mspx
|archive-date = May 17, 2009
|url-status=dead
|df = mdy-all
}}</ref> with the exception of a list of products that do not explicitly mention C#, .NET or Novell's implementation of .NET ([[Mono (software)|The Mono Project]]).<ref>{{cite web
| url = http://www.microsoft.com/interop/msnovellcollab/definitions2.aspx
| title = Definitions
| date = November 2, 2006
| publisher = [[Microsoft]]
| access-date = July 5, 2009
| archive-date = November 4, 2012
| archive-url = https://web.archive.org/web/20121104185826/http://www.microsoft.com/interop/msnovellcollab/definitions2.aspx
| url-status = live
}}</ref> However, Novell maintained that Mono does not infringe any Microsoft patents.<ref>{{cite web
| url = http://www.novell.com/linux/microsoft/faq_opensource.html
| title = Novell Answers Questions from the Community
| first = Justin
| last = Steinman
| date = November 7, 2006
| access-date = July 5, 2009
| quote = We maintain that Mono does not infringe any Microsoft patents.
| archive-date = July 16, 2013
| archive-url = https://web.archive.org/web/20130716165922/https://www.suse.com/company/press/2011/7/microsoft-and-suse-renew-successful-interoperability-agreement.html
| url-status = live
}}</ref> Microsoft also made a specific agreement not to enforce patent rights related to the [[Moonlight (runtime)|Moonlight browser plugin]], which depends on Mono, provided it is obtained through Novell.<ref name="MsCovenant">{{cite web
|url = http://www.microsoft.com/interop/msnovellcollab/moonlight.mspx
|title = Covenant to Downstream Recipients of Moonlight - Microsoft & Novell Interoperability Collaboration
|publisher = [[Microsoft]]
|quote = "Downstream Recipient" means an entity or individual that uses for its intended purpose a Moonlight Implementation obtained directly from Novell or through an Intermediate Recipient... Microsoft reserves the right to update (including discontinue) the foregoing covenant... "Moonlight Implementation" means only those specific portions of Moonlight 1.0 or Moonlight 1.1 that run only as a plug-in to a browser on a Personal Computer and are not licensed under GPLv3 or a Similar License.
|date = September 28, 2007
|access-date = March 8, 2008
|archive-url = https://web.archive.org/web/20100923213336/http://www.microsoft.com/interop/msnovellcollab/moonlight.mspx
|archive-date = September 23, 2010
|url-status=dead
|df = mdy-all
}}</ref>
 
A decade later, Microsoft began developing free, open-source, and cross-platform tooling for C#, namely [[Visual Studio Code]], [[.NET Core]], and [[Roslyn (compiler)|Roslyn]]. Mono joined Microsoft as a project of [[Xamarin]], a Microsoft subsidiary.
 
==Implementations==
Microsoft has developed [[Open-source software|open-source]] reference C# compilers and tools. The first compiler, [[Microsoft Roslyn|Roslyn]], compiles into intermediate language (IL), and the second one, RyuJIT,<ref name="bruce">{{cite web |url=https://devblogs.microsoft.com/dotnet/the-ryujit-transition-is-complete/ |title=The RyuJIT transition is complete! |website=microsoft.com |date=June 19, 2018 |access-date=July 20, 2021 |url-status=live|archive-url=https://web.archive.org/web/20190719034140/https://devblogs.microsoft.com/dotnet/the-ryujit-transition-is-complete/ |archive-date=July 19, 2019 }}</ref> is a JIT (just-in-time) compiler, which is dynamic and does on-the-fly optimization and compiles the IL into native code for the front-end of the CPU.<ref>{{cite web |url=https://docs.microsoft.com/en-us/dotnet/standard/managed-execution-process |title=Managed Execution Process |website=microsoft.com |access-date=July 20, 2021 |url-status=live|archive-url=https://web.archive.org/web/20171223005925/https://docs.microsoft.com/en-us/dotnet/standard/managed-execution-process |archive-date=December 23, 2017 }}</ref> RyuJIT is open source and written in C++.<ref>{{cite web |url=https://github.com/dotnet/coreclr/tree/master/src/jit |title=coreclr/src/jit/ |website=github.com |access-date=July 20, 2021 |url-status=live|archive-url=https://web.archive.org/web/20190109215901/https://github.com/dotnet/coreclr/tree/master/src/jit |archive-date=January 9, 2019 }}</ref> Roslyn is entirely written in [[managed code]] (C#), has been opened up and functionality surfaced as APIs. It is thus enabling developers to create refactoring and diagnostics tools.<ref name="auto"/><ref>{{Cite web|url=https://docs.microsoft.com/en-us/dotnet/csharp/|title=C# Guide|website=Microsoft Learn|access-date=July 28, 2017|archive-date=August 13, 2022|archive-url=https://web.archive.org/web/20220813004950/https://docs.microsoft.com/en-us/dotnet/csharp/|url-status=live}}</ref> Two branches of official implementation are .NET Framework (closed-source, Windows-only) and .NET Core (open-source, cross-platform); they eventually converged into one open-source implementation: .NET 5.0.<ref>{{cite web |url=https://dotnet.microsoft.com/download/dotnet/5.0 |title=5.0.8 |website=microsoft.com |access-date=July 20, 2021 |url-status=live|archive-url=https://web.archive.org/web/20200423133947/https://dotnet.microsoft.com/download/dotnet/5.0 |archive-date=April 23, 2020 }}</ref> At .NET Framework 4.6, a new JIT compiler replaced the former.<ref name="bruce"/><ref>{{cite web |url=https://docs.microsoft.com/en-us/dotnet/framework/migration-guide/mitigation-new-64-bit-jit-compiler |title=Mitigation: New 64-bit JIT Compiler |website=microsoft.com |access-date=July 20, 2021 |url-status=live|archive-url=https://web.archive.org/web/20180405142913/https://docs.microsoft.com/en-us/dotnet/framework/migration-guide/mitigation-new-64-bit-jit-compiler |archive-date=April 5, 2018 }}</ref>
 
Other C# compilers (some of which include an implementation of the [[Common Language Infrastructure]] and .NET class libraries):
* [[Mono (software)|Mono]], a Microsoft-sponsored project provides an open-source C# compiler, a complete open-source implementation of the CLI (including the required framework libraries as they appear in the ECMA specification,) and a nearly complete implementation of the NET class libraries up to .NET Framework 3.5.
* The [[Elements (toolchain)|Elements]] tool chain from [[RemObjects]] includes RemObjects C#, which compiles C# code to .NET's [[Common Intermediate Language]], [[Java bytecode]], [[Cocoa (API)|Cocoa]], [[Dalvik (software)|Android bytecode]], [[WebAssembly]], and native machine code for Windows, macOS, and Linux.
*The [[DotGNU]] project (now discontinued) also provided an open-source C# compiler, a nearly complete implementation of the Common Language Infrastructure including the required framework libraries as they appear in the ECMA specification, and subset of some of the remaining Microsoft proprietary .NET class libraries up to .NET 2.0 (those not documented or included in the ECMA specification, but included in Microsoft's standard .NET Framework distribution).
The [[Unity (game engine)|Unity game engine]] uses C# as its primary scripting language. The [[Godot (game engine)|Godot game engine]] has implemented an optional C# module due to a donation of $24,000 from Microsoft.<ref>{{cite news|title=Introducing C# in Godot |work=[[Godot (game engine)|Godot Engine]] |url=https://godotengine.org/article/introducing-csharp-godot |access-date=October 26, 2018 |url-status=live |archive-url=https://web.archive.org/web/20181026084022/https://godotengine.org/article/introducing-csharp-godot |archive-date=October 26, 2018 |date=October 21, 2017|first1=Ignacio|last1=Etcheverry}}</ref>
 
==See also==
{{Portal|Computer programming}}
 
{{col-float}}
 
;C# topics
* [[C Sharp syntax|C# syntax]]
* [[Comparison of C Sharp and Java|Comparison of C# and Java]]
* [[Comparison of C Sharp and Visual Basic .NET|Comparison of C# and Visual Basic .NET]]
* [[Standard Libraries (CLI)|.NET standard libraries]]
 
{{col-float-break}}
 
;IDEs
* [[Visual Studio]]
* [[Visual Studio Code]]
* [[JetBrains#Rider|Rider]]
* [[LINQPad]]
* [[MonoDevelop]]
* [[Morfik]]
* [[SharpDevelop]]
* [[Turbo C Sharp|Turbo C#]]
* [[Microsoft Visual Studio Express]]
* [[Xamarin Studio]]
 
{{col-float-end}}
{{Clear}}
 
==Notes==
{{Notelist}}
 
== References ==
 
=== Citations ===
 
{{Reflist|30em|refs=
 
<ref name="dynamic">{{cite web |url = http://code.msdn.microsoft.com/csharpfuture/Release/ProjectReleases.aspx?ReleaseId=1686 |title = New features in C# 4.0 |first = Mads |last = Torgersen |date = October 27, 2008 |publisher = [[Microsoft]] |access-date = October 28, 2008 |archive-date = January 3, 2012 |archive-url = https://web.archive.org/web/20120103195731/http://code.msdn.microsoft.com/csharpfuture/Release/ProjectReleases.aspx?ReleaseId=1686 |url-status = dead }}</ref>
 
<ref name="influenced by CPP">{{cite journal |last=Naugler |first=David |date=May 2007 |title=C# 2.0 for C++ and Java programmer: conference workshop |journal=Journal of Computing Sciences in Colleges |volume=22 |issue=5 |quote=Although C# has been strongly influenced by Java it has also been strongly influenced by C++ and is best viewed as a descendant of both C++ and Java.}}</ref>
 
<ref name="influenced by op">{{cite magazine |url = http://www.computerworld.com.au/article/261958/a-z_programming_languages_c_/?pp=7 |title = The A-Z of Programming Languages: C# |date = October 1, 2008 |magazine = [[Computerworld]] |first = Naomi |last = Hamilton |access-date = February 12, 2010 |quote = We all stand on the shoulders of giants here and every language builds on what went before it so we owe a lot to C, C++, Java, Delphi, all of these other things that came before us. ([[Anders Hejlsberg]]) |archive-date = March 24, 2010 |archive-url = https://web.archive.org/web/20100324124903/http://www.computerworld.com.au/article/261958/a-z_programming_languages_c_/?pp=7 |url-status = dead }}</ref>
 
<ref name="influenced">{{cite web |url = http://www.barrycornelius.com/papers/java5/onefile/ |title = Java 5 catches up with C# |date = December 1, 2005 |publisher = [[University of Oxford]] Computing Services |first = Barry |last = Cornelius |access-date = June 18, 2014 |quote = In my opinion, it is C# that has caused these radical changes to the Java language. ([[Barry Cornelius]]) |archive-date = March 6, 2023 |archive-url = https://web.archive.org/web/20230306045428/http://www.barrycornelius.com/papers/java5/onefile/ |url-status = live }}</ref>
}}
 
=== Sources ===
 
* {{cite book |last=Albahari |first=Joseph |title= C# 10 in a Nutshell |publisher= O'Reilly |isbn= 978-1-098-12195-2|edition=First|year=2022}}
*{{cite book| last = Archer| first = Tom| title = Inside C#| year = 2001| publisher = Microsoft Press|___location=Redmond, Washington|isbn=0-7356-1288-9|chapter=Part 2, Chapter 4: The Type System}}
*{{cite book|last1=Novák |first1=István| last2=Velvart|first2=Andras| first3=Adam| last3=Granicz| first4=György| last4=Balássy| first5=Attila |last5=Hajdrik| first6=Mitchel| last6=Sellers| first7=Gastón C. |last7=Hillar| first8=Ágnes |last8=Molnár| first9=Joydip| last9=Kanjilal|title=Visual Studio 2010 and .NET 4 Six-in-One|year=2010|publisher=Wrox Press|isbn=978-0470499481}}
*{{cite book |last=Skeet|first=Jon|title= C# in Depth|edition=Fourth|publisher= Manning |isbn= 978-1617294532|year=2019}}
 
== Further reading ==
 
* {{cite book | title = C# Language Pocket Reference| url = https://archive.org/details/clanguagepocketr00pete| url-access = registration| first1=Peter | last1=Drayton | first2=Ben | last2=Albahari | first3=Ted | last3=Neward| year=2002| publisher = O'Reilly| isbn=0-596-00429-X}}
* {{cite book| title=Programming Microsoft Windows with C#| last=Petzold| first=Charles| year=2002| publisher=Microsoft Press| isbn=0-7356-1370-2| url-access=registration| url=https://archive.org/details/isbn_9780735613706}}
 
==External links==
* [https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/introduction C# Language Specification]
* [https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/ C# Programming Guide]
* [https://standards.iso.org/ittf/PubliclyAvailableStandards/c075178_ISO_IEC_23270_2018.zip ISO C# Language Specification]
* [https://github.com/dotnet/roslyn C# Compiler Platform ("Roslyn") source code]
 
{{Common Language Infrastructure}}
{{Microsoft FOSS}}
{{Ecma International Standards}}
{{ISO standards}}
{{Programming languages}}
{{List of International Electrotechnical Commission standards}}
{{Authority control}}
 
[[Category:C Sharp programming language family| ]]
[[Category:2000 software]]
[[Category:American inventions]]
[[Category:Programming languages]]
[[Category:High-level programming languages]]
[[Category:.NET programming languages]]
[[Category:ConcurrentClass-based programming languages]]
[[Category:CEcma programming language familystandards]]
[[Category:Curly bracket programmingFunctional languages]]
[[Category:ISO standards]]
[[Category:IEC standards]]
[[Category:ISO standards]]
 
[[Category:Microsoft programming languages]]
[[bg:C Sharp]]
[[Category:Multi-paradigm programming languages]]
[[cs:Csharp]]
[[Category:Programming languages created in 2000]]
[[da:C Sharp]]
[[Category:Programming languages with an ISO standard]]
[[de:C-Sharp]]
[[Category:Statically typed programming languages]]
[[es:C Sharp]]
[[Category:Compiled programming languages]]
[[eo:C dieso (programlingvo)]]
<!-- Hidden categories below -->
[[fr:C sharp]]
[[Category:Articles with example C Sharp code]]
[[ko:C 샤프]]
[[it:C sharp]]
[[he:C Sharp]]
[[lt:C sharp]]
[[hu:C Sharp programozási nyelv]]
[[nl:C sharp]]
[[ja:C Sharp]]
[[no:C Sharp]]
[[pl:C Sharp]]
[[pt:C sharp]]
[[ru:C Sharp]]
[[sk:C Sharp (programovací jazyk)]]
[[sr:C Sharp]]
[[fi:C sharp]]
[[sv:C-sharp]]
[[th:ภาษาซีชาร์ป]]
[[vi:C thăng]]
[[tr:C Sharp programlama dili]]
[[uk:C Sharp]]
[[zh:C#]]