C Sharp (programming language)#Hello World
{{Short description|Programming language}}
{{Correct title|title=C#|reason=#}}
{{Use mdy dates|date= April 2020}}
{{Infobox programming language
| name = C#
| logo = C_Sharp_Logo_2023.svg
| logo size = 165px
| paradigm = Multi-paradigm: structured, imperative, object-oriented, event-driven, task-driven, functional, generic, reflective, concurrent
| family = C
| year = {{start date and age|2000}}{{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 }}
| 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, dynamic, strong, safe, nominative, partly inferred
| memory management = automatic memory management
| implementations = Visual C#, .NET, Mono, Universal Windows Platform
Discontinued: .NET Framework, DotGNU
| dialects = Cω, Polyphonic C#, [http://ecsharp.net Enhanced C#]
| influenced_by = C++, Cω, Eiffel, F#,{{efn|for async}} Haskell, Scala, Icon, J#, J++, Java, JavaScript, ML, Modula-3, Object Pascal, VB
| influenced = Chapel,{{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}} Clojure,{{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}} Crystal,{{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
}} D, J#, Dart,{{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}} F#, Hack, Java,Java 5.0 added several new language features (the enhanced for loop, autoboxing, varargs and 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 }} Kotlin, Nemerle, Oxygene, Rust,{{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 }} Swift,{{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}} Vala, TypeScript
| platform = Common Language Infrastructure
| license = {{plainlist|
- Roslyn compiler: MIT/X11{{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}}
- .NET Core CLR: MIT/X11{{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}}
- Mono compiler: dual GPLv3 and MIT/X11
- DotGNU: dual GPL and LGPL
}}
| file_ext = .cs
, .csx
| 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 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 high-level programming language supporting multiple paradigms. C# encompasses static typing,{{sfn|Skeet|2019}}{{rp|4}} strong typing, lexically scoped, imperative, declarative, functional, generic,{{sfn|Skeet|2019}}{{rp|22}} object-oriented (class-based), and component-oriented programming disciplines.
The principal inventors of the C# programming language were Anders Hejlsberg, Scott Wiltamuth, and Peter Golde from Microsoft. It was first widely distributed in July 2000 and was later approved as an international standard by Ecma (ECMA-334) in 2002 and ISO/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, 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 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), and 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.
{{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{{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 }}{{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 }}
Design goals
The Ecma standard lists these design goals for C#:{{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 }}
- The language is intended to be a simple, modern, general-purpose, object-oriented programming language.
- The language, and implementations thereof, should provide support for software engineering principles such as strong type checking, array bounds checking,{{sfn|Albahari|2022}}{{rp|58–59}} detection of attempts to use uninitialized variables, and automatic garbage collection.{{sfn|Albahari|2022}}{{rp|563}} Software robustness, durability, and programmer productivity are important.
- The language is intended for use in developing software components suitable for deployment in distributed environments.
- Portability is very important for source code and programmers, especially those already familiar with C and C++.
- Support for internationalization{{sfn|Albahari|2022}}{{rp|314}} is very important.
- C# is intended to be suitable for writing applications for both hosted and embedded systems, ranging from the very large that use sophisticated operating systems, down to the very small having dedicated functions.
- Although C# applications are intended to be economical with regard to memory and processing power requirements, the language was not intended to compete directly on performance and size with C or assembly language.{{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}}
History
{{Multiple image
| footer = C#'s former logos
|image1 = Logo C sharp.svg
|width1 = 90
|image2 = C Sharp wordmark.svg
|width2 = 100
}}
During the development of the .NET Framework, the class libraries were originally written using a managed code compiler system named Simple Managed C (SMC).{{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= November 22, 2007
|access-date= February 23, 2009
|archive-date= July 29, 2020
|archive-url= https://web.archive.org/web/20200729002618/https://docs.microsoft.com/en-us/archive/blogs/jasonz/couple-of-historical-facts
|url-status= live
|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= June 24, 2016
|title= What language was ASP.Net originally written in?
|date= November 28, 2006
|first=
|last=
|author-link= Scott Guthrie
|access-date= February 21, 2008
}} In January 1999, Anders Hejlsberg formed a team to build a new language at the time called COOL, which stood for "C-like Object Oriented Language".{{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= October 1, 2008
|access-date= October 1, 2008
|archive-url=https://web.archive.org/web/20190518115808/https://www.computerworld.com.au/article/261958/a-z_programming_languages_c_/
|archive-date=18 May 2019 |url-status=dead}} 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#.
Hejlsberg is C#'s principal designer and lead architect at Microsoft, and was previously involved with the design of Turbo Pascal, Embarcadero Delphi (formerly CodeGear Delphi, Inprise Delphi and Borland Delphi), and Visual J++. In interviews and technical papers, he has stated that flaws{{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}} in most major programming languages (e.g. C++, Java, Delphi, and Smalltalk) drove the fundamentals of the Common Language Runtime (CLR), which, in turn, drove the design of the C# language.
James Gosling, who created the 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 that "[C# is] sort of Java with reliability, productivity and security deleted."{{cite web
|url=https://www.cnet.com/tech/tech-industry/why-microsofts-c-isnt/
|title=Why Microsoft's C# isn't
|publisher=CNET: CBS Interactive
|year=2002
|access-date=September 18, 2023
|archive-date=August 14, 2023
|archive-url=https://web.archive.org/web/20230814054213/https://www.cnet.com/tech/tech-industry/why-microsofts-c-isnt/
|url-status=live
|url= https://www.cnet.com/tech/tech-industry/microsofts-blind-spot/
|title= Microsoft's blind spot
|author= Bill Joy
|publisher= cnet.com
|date= February 7, 2002
|access-date= September 18, 2023
|author-link= Bill Joy
|archive-date= August 14, 2023
|archive-url= https://web.archive.org/web/20230814053108/https://www.cnet.com/tech/tech-industry/microsofts-blind-spot/
|url-status= live
}}
In July 2000, Hejlsberg said that C# is "not a Java clone" and is "much closer to C++" in its design.{{Cite news
|last= Osborn
|first= John
|date= August 1, 2000
|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= November 14, 2009
|archive-date= January 9, 2010
|archive-url= https://web.archive.org/web/20100109195800/http://windowsdevcenter.com/pub/a/oreilly/windows/news/hejlsberg_0800.html
|url-status= live
}}
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 generics to both languages, with vastly different implementations. C# uses of reification to provide "first-class" generic objects that can be used like any other class, with code generation performed at class-load time.{{cite web
| url = http://msdn.microsoft.com/en-us/library/512aeb7t.aspx
| title = Generics (C# Programming Guide)
| publisher = Microsoft
| access-date = March 21, 2011
| archive-date = August 26, 2011
| archive-url = https://web.archive.org/web/20110826233800/http://msdn.microsoft.com/en-us/library/512aeb7t.aspx
| url-status = live
}}
Furthermore, C# has added several major features to accommodate functional-style programming, culminating in the LINQ extensions released with C# 3.0 and its supporting framework of lambda expressions, extension methods, and anonymous types.{{cite web
| 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 = March 21, 2011
| archive-date = August 24, 2011
| archive-url = https://web.archive.org/web/20110824063725/http://msdn.microsoft.com/en-us/library/bb308959.aspx
| url-status = live
}} These features enable C# programmers to use functional programming techniques, such as 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.{{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 = April 15, 2010
| access-date = March 21, 2011
| archive-date = July 11, 2011
| 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
}}
C# used to have a mascot called Andy (named after Anders Hejlsberg). It was retired on January 29, 2004.{{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=January 29, 2004 |access-date=October 4, 2012|archive-url=https://web.archive.org/web/20160119144858if_/http://blogs.msdn.com/b/danielfe/archive/2004/01/29/64429.aspx|archive-date=January 19, 2016}}
C# was originally submitted to the ISO/IEC JTC 1 subcommittee SC 22 for review,{{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 }} under ISO/IEC 23270:2003,{{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 }} was withdrawn and was then approved under ISO/IEC 23270:2006.{{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 }} The 23270:2006 is withdrawn under 23270:2018 and approved with this version.{{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}}
=Name=
Microsoft first used the name C# in 1988 for a variant of the C language designed for incremental compilation.{{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}} That project was not completed, and the name was later reused.
The name "C sharp" was inspired by the musical notation whereby a sharp symbol indicates that the written note should be made a semitone higher in pitch.{{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
}}
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 ligature of four "+" symbols (in a two-by-two grid), further implying that the language is an increment of C++.{{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
}}
Due to technical limits of display (standard fonts, browsers, etc.), and most keyboard layouts 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.{{cite web
|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
}}
This convention is reflected in the ECMA-334 C# Language Specification.
The "sharp" suffix has been used by a number of other Microsoft .NET compatible/compliant languages that are variants of existing languages, including J# (a .NET language also designed by Microsoft that is derived from Java 1.1), A# (from Ada), and the functional programming language F#.{{cite web
|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
}} The original implementation of Eiffel for .NET was called Eiffel#,{{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
}} a name retired since the full Eiffel language is now supported. The suffix has also been used for libraries, such as Gtk# (a .NET wrapper for GTK and other GNOME libraries) and Cocoa# (a wrapper for Cocoa).
=Versions=
Development of the text for standards (beginning with C# 6) is done on [https://github.com/dotnet/csharpstandard GitHub]. C# 7 was submitted to Ecma and approved in December 2023. As of January 2024, the standard for C# 8 is currently under development, referencing the [https://github.com/dotnet/csharplang/tree/main/proposals approved language proposals].
Syntax
{{Main|C Sharp syntax|l1 = C# syntax}}
{{See also|Syntax (programming languages)}}
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.
- 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 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
{{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=
By design, C# is the programming language that most directly reflects the underlying Common Language Infrastructure (CLI).{{sfn|Novák|Velvart|Granicz|Balássy|2010}} Most of its intrinsic types correspond to value-types implemented by the 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 (CLR), or generate 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.{{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 }}{{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 }}
=Typing=
C# supports strongly, implicitly typed variable declarations with the keyword var
,{{sfn|Skeet|2019}}{{rp|470}} and implicitly typed arrays with the keyword new[]
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 immutability, strings will nevertheless behave as if they were values, for all practical purposes. You can even use them as case labels. Where necessary, value types will be boxed automatically.{{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}}
C# supports a strict Boolean data type, bool
. Statements that take conditions, such as while
and if
, require an expression of a type that implements the true
operator, such as the Boolean type. While C++ also has a Boolean type, it can be freely converted to and from integers, and expressions such as if (a)
require only that a
is convertible to bool, allowing a
to be an int, or a pointer. C# disallows this "integer meaning true or false" approach, on the grounds that forcing programmers to use expressions that return exactly bool
can prevent certain types of programming mistakes such as if (a = b)
(use of assignment =
instead of equality ==
).
C# is more type safe than C++. The only implicit conversions by default are those that are considered safe, such as widening of integers. This is enforced at compile-time, during 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 constructors and conversion operators, which are both implicit by default.
C# has explicit support for 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.
Enumeration members are placed in their own scope.
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.
Local variables cannot shadow variables of the enclosing block, unlike C and C++, but may shadow type-level names.
=Metaprogramming=
Metaprogramming can be achieved in several ways:
- Reflection is supported through .NET APIs, which enable scenarios such as type metadata inspection and dynamic method invocation.
- Expression trees{{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}} 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.
- Attributes, in C# parlance, are metadata that can be attached to types, members, or entire assemblies, equivalent to annotations in Java. Attributes are accessible both to the compiler and to code through reflection, allowing them to adjust their behaviour.{{Cite web|url=https://learn.microsoft.com/en-us/dotnet/api/system.attribute|title=Attribute Class}} Many of the native attributes duplicate the functionality of GCC's and VisualC++'s platform-dependent preprocessor directives.{{Citation needed|date=March 2022}}
System.Reflection.Emit
namespace,{{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 }} which contains classes that emit metadata and CIL (types, assemblies, etc.) at runtime.- 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 of code, semantic analysis, dynamic compilation to CIL, and code emission.{{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 }}
- Source generators,{{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}} 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=
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 or instance variable).{{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 }} 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 private
), the explicit specification of its return type (such as int
, or the keyword void
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, call-by-reference parameters have to be marked both at the function definition and at the calling site, and you can choose between ref
and out
, the latter allowing handing over an uninitialized variable which will have a definite value on return.{{cite web|url=https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/out|title=out (C# Reference)|date=March 30, 2024 }} Additionally, you can specify a variable-sized argument list by applying the params
keyword to the last parameter.{{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 }} 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.{{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 }}
Like C++, and unlike Java, C# programmers must use the scope modifier keyword virtual
to allow methods to be overridden by subclasses. Unlike C++, you have to explicitly specify the keyword override
when doing so.{{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}} This is supposed to avoid confusion between overriding and newly overloading a function (i.e. hiding the former implementation). To do the latter, you have to specify the new
keyword.{{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 }} You can use the keyword sealed
to disallow further overrides for individual methods or whole classes.{{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 }}
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}}
The type dynamic
allows for run-time method binding, allowing for JavaScript-like method calls and run-time object composition.{{sfn|Skeet|2019}}{{rp|114–118}}
C# has support for strongly-typed function pointers via the keyword delegate
. Like the Qt framework's pseudo-C++ signal and slot, C# has semantics specifically surrounding publish-subscribe style events, though C# uses delegates to do so.
C# offers Java-like synchronized
method calls, via the attribute [MethodImpl(MethodImplOptions.Synchronized)]
, and has support for mutually-exclusive locks via the keyword lock
.
=Property=
C# supports classes with properties. The properties can be simple accesor 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 virtual
or abstract
like any other method.
Since C# 3.0 the syntactic sugar of auto-implemented properties is available,{{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}} where the accessor (getter) and mutator (setter) encapsulate operations on a single field of a class.
=Namespace=
A C# namespace
provides the same level of code isolation as a Java package
or a C++ {{C++|namespace}}, with very similar rules and features to a package
. Namespaces can be imported with the "using" syntax.{{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}}
=Memory access=
In C#, memory address pointers can only be used within blocks specifically marked as unsafe,{{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}} 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 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 System.IntPtr
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 leaks 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.{{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}}
The syntax for handling exceptions is the following:
{
// something
}
catch (Exception ex)
{
// if error do this
}
finally
{
// always executes, regardless of error occurrence
}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.
try
{
// something here
}
catch (Exception ex)
{
// example
return 0;
}
finally
{
return 1;
}
Depending on your plans, the "finally" part can be left out. If error handling is not required, the (Exception ex)
parameter can be omitted as well. Also, there can be several "catch" parts handling different kinds of exceptions.{{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 }}
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.{{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
}}
=Polymorphism=
Unlike C++, C# does not support multiple inheritance, although a class can implement any number of "interfaces" (fully abstract classes). This was a design decision by the language's lead architect to avoid complications and to simplify architectural requirements throughout CLI.
When implementing multiple interfaces that contain a method with the same name and taking parameters of the same type in the same order (i.e. the same signature), similar to 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), i.e. methods with the same name, but distinguishable signatures.{{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}} Unlike Java, C# additionally supports operator overloading.{{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}}
Since version 2.0, C# offers parametric polymorphism, i.e. classes with arbitrary or constrained type parameters, e.g. List
, a variable-sized array which only can contain elements of type T
. There are certain kinds of constraints you can specify for the type parameters: Has to be type X (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. Most of them can be combined, and you can specify any number of interfaces.{{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}}{{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}}
=Language Integrated Query (LINQ)=
C# has the ability to utilize LINQ through the .NET Framework. A developer can query a variety of data sources, provided the IEnumerable<T>
interface is implemented on the object. This includes XML documents, an ADO.NET dataset, and SQL databases.{{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 }}
Using 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.{{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}} }} 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.{{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}} }}
LINQ has two syntaxes: query syntax and method syntax. However, the compiler always converts the query syntax to method syntax at compile time.{{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 }}
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);
=Functional programming=
Though primarily an imperative language, C# always adds functional features over time,{{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 }}{{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 }} for example:
- Functions as first-class citizen – C# 1.0 delegates{{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 }}
- Higher-order functions – C# 1.0 together with delegates
- Anonymous functions – C# 2 anonymous delegates and C# 3 lambdas expressions{{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 }}
- Closures – C# 2 together with anonymous delegates and C# 3 together with lambdas expressions
- 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
- Tuples – .NET Framework 4.0 but it becomes popular when C# 7.0 introduced a new tuple type with language support{{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 }}
- Nested functions – C# 7.0
- Pattern matching – C# 7.0
- Immutability – C# 7.2 readonly struct C# 9 record types{{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 }} and Init only setters{{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 }}
- Type classes – C# 12 roles/extensions (in development{{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 }})
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), decimal
(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 cast. A boxed object of type T can only be unboxed to a T (or a nullable T).{{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 }}
Example:
int foo = 42; // Value type.
object bar = foo; // foo is boxed to bar.
int foo2 = (int)bar; // Unboxed back to value type.
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.{{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}}
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" 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:{{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}}
System.Console.WriteLine("Hello, world!");
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:
using System;
class Program
{
static void Main()
{
Console.WriteLine("Hello, world!");
}
}
This code will display this text in the console window:
Hello, world!
Each line has a purpose:
using System;
The above line imports all types in the System
namespace. For example, the Console
class used later in the source code is defined in the System
namespace, meaning it can be used without supplying the full name of the type (which includes the namespace).
// A version of the classic "Hello World" program
This line is a comment; it describes and documents the code for the programmer(s).
class Program
Above is a class definition for the {{C sharp|Program}} class. Everything that follows between the pair of braces describes that class.
{
...
}
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.
static void Main()
This declares the class member method where the program begins execution. The .NET runtime calls the {{C sharp|Main}} method. Unlike in 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.{{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}} Writing {{C sharp|static void Main(string[] args)}} is equivalent to writing {{C sharp|private static void Main(string[] args)}}. The 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 applications (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.)
Console.WriteLine("Hello, world!");
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.{{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}}
Example
public class DataStore
{
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];
}
}
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 ISO/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 generics (somewhat similar to C++ 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 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.{{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}} Microsoft has also agreed not to enforce patents relating to Novell products against Novell's paying customers{{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
}} with the exception of a list of products that do not explicitly mention C#, .NET or Novell's implementation of .NET (The Mono Project).{{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
}} However, Novell maintained that Mono does not infringe any Microsoft patents.{{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
}} Microsoft also made a specific agreement not to enforce patent rights related to the Moonlight browser plugin, which depends on Mono, provided it is obtained through Novell.{{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
}}
A decade later, Microsoft began developing free, open-source, and cross-platform tooling for C#, namely Visual Studio Code, .NET Core, and Roslyn. Mono joined Microsoft as a project of Xamarin, a Microsoft subsidiary.
Implementations
Microsoft has developed open-source reference C# compilers and tools. The first compiler, Roslyn, compiles into intermediate language (IL), and the second one, RyuJIT,{{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 }} 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.{{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 }} RyuJIT is open source and written in C++.{{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 }} 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.{{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}} 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.{{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 }} At .NET Framework 4.6, a new JIT compiler replaced the former.{{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 }}
Other C# compilers (some of which include an implementation of the Common Language Infrastructure and .NET class libraries):
- 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 tool chain from RemObjects includes RemObjects C#, which compiles C# code to .NET's Common Intermediate Language, Java bytecode, Cocoa, 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 uses C# as its primary scripting language. The Godot game engine has implemented an optional C# module due to a donation of $24,000 from Microsoft.{{cite news|title=Introducing C# in Godot |work=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}}
See also
{{Portal|Computer programming}}
{{col-float}}
;C# topics
{{col-float-break}}
;IDEs
- Visual Studio
- Visual Studio Code
- Rider
- LINQPad
- MonoDevelop
- Morfik
- SharpDevelop
- Turbo C#
- Microsoft Visual Studio Express
- Xamarin Studio
{{col-float-end}}
{{Clear}}
Notes
{{Notelist}}
References
= Citations =
{{Reflist|30em|refs=
{{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 }}
{{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 }}
{{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 }}
}}
= 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:Programming languages
Category:High-level programming languages
Category:.NET programming languages
Category:Class-based programming languages
Category:Microsoft programming languages
Category:Multi-paradigm programming languages
Category:Programming languages created in 2000
Category:Programming languages with an ISO standard
Category:Statically typed programming languages