Fact-checked by Grok 2 weeks ago

C-sharp

C# (pronounced "C Sharp") is a simple, modern, general-purpose, language designed by to support robust and durable software components. Developed as part of the .NET Framework initiative, it enables the creation of a wide range of applications, from desktop and web to mobile and cloud-based systems, while emphasizing , garbage collection, and portability for developers familiar with languages like C and C++. The language has evolved into an open-source, cross-platform standard, approved by (ECMA-334) and the (ISO/IEC 23270). The principal designers of C# were Anders Hejlsberg, Scott Wiltamuth, and Peter Golde, who began work on the language in 2000 under Microsoft's .NET project. The first implementation was released in July 2000, with the official version 1.0 launching in January 2002 alongside .NET Framework 1.0 and Visual Studio .NET. Since then, C# has seen annual major releases, incorporating features like generics (C# 2.0, 2005), LINQ and lambda expressions (C# 3.0, 2007), async/await (C# 5.0, 2012), and records with top-level statements (C# 9.0, 2020). As of November 2025, the latest version is C# 14, integrated with .NET 10, which introduces enhancements for productivity, such as improved pattern matching and file-based application structures. C# supports multiple programming paradigms, including functional, declarative, and component-oriented approaches, alongside its core object-oriented foundation with classes, interfaces, and inheritance. Key features include strong typing with compile-time checks, automatic via garbage collection, for querying data, async programming for scalable applications, and modern constructs like , tuples, and collection expressions. It runs on the cross-platform .NET runtime, enabling development for Windows, , macOS, , , and web via tools like , with support from integrated development environments such as and . Widely adopted by millions of developers and thousands of companies in sectors like finance, gaming, and healthcare, C# ranks among the most popular languages, powering high-performance applications that process billions of requests daily.

History

Origins and design goals

C# was developed by Microsoft in the late 1990s as a modern programming language designed to leverage the emerging .NET Framework, with its first public release occurring in July 2000 alongside the framework's launch. The principal designers were Anders Hejlsberg, Scott Wiltamuth, and Peter Golde, who drew significant influences from C and C++ to ensure familiarity for experienced programmers, while incorporating elements from Java through Hejlsberg's prior work on Microsoft's Visual J++, a Java development tool that faced legal challenges and was eventually deprecated. Hejlsberg's experience with Delphi, where he served as chief architect, also shaped C#'s emphasis on component-oriented design and developer productivity. The core design goals of C# centered on creating a simple, modern, general-purpose, object-oriented language that prioritizes , automatic garbage collection, and robust error handling to enhance developer productivity and software reliability. It aimed to support component-oriented programming by enabling the creation of reusable, versionable software components that could evolve without breaking existing code, while providing a clean syntax that avoids the complexities of C++ such as . Additional objectives included facilitating , source code portability across platforms, and , making it suitable for building applications in hosted and embedded environments. C# was fundamentally tied to the .NET Framework and its (CLR), now part of the broader (CLI), which provides the environment, libraries, and execution model essential for the language's operation. Early development involved prototypes influenced by internal projects, including extensions from Visual J++ efforts, to create a safe, managed alternative to C++ tailored for the .NET ecosystem. This integration with CLR ensured features like garbage collection and were enforced at , aligning with the goal of reducing common programming errors.

Naming and early development

The name "C#" derives from the musical note C♯, selected for its brevity, branding potential, and to evoke a "sharp" advancement over predecessors like C and C++, reflecting the language's aim to provide a modern, component-oriented evolution in the C family. Prior to this, the project bore the internal codename "Cool," an acronym for "C-like Object Oriented Language," which was used during initial development but abandoned for the final name to better align with marketing and design aspirations. Development of C# commenced in 2000 at , when , previously known for and at , assembled a team to design a new language tailored for the emerging .NET platform. The first public preview occurred at Microsoft's Professional Developers Conference (PDC) in July 2000, where Hejlsberg demonstrated the language's core features to developers, generating immediate interest for its productivity enhancements over existing tools. C# 1.0 was officially released on January 15, 2002, coinciding with Visual Studio .NET 2002 and the .NET Framework 1.0, marking its integration into enterprise development workflows. The initial C# compiler, csc.exe, was tightly integrated with Visual Studio .NET, offering syntax highlighting, IntelliSense, debugging, and project management tools that streamlined compilation and deployment for Windows-based applications. This IDE support was crucial for early users transitioning from languages like C++ or , enabling faster iteration despite the novelty of the .NET . Early of C# encountered hurdles, including perceptions of it as a Java derivative amid antitrust scrutiny on , and resistance from developers accustomed to unmanaged code in C++. Community feedback praised its and simplicity but noted initial performance overheads in the managed environment and limited cross-platform support, prompting rapid iterations. Standardization by in April 2002 further bolstered credibility and encouraged wider experimentation.

Version history

C# 1.0 was released in January 2002 alongside .NET Framework 1.0, introducing core constructs such as classes, interfaces, and , along with delegates and for event handling. C# 2.0 arrived in November 2005 with .NET Framework 2.0, adding generics for type-safe collections, anonymous methods for inline delegates, and iterators using the yield keyword to simplify sequence generation. The release of C# 3.0 in November 2007, tied to .NET Framework 3.5, brought (LINQ) for querying data sources, lambda expressions for concise function definitions, and extension methods to augment existing types. C# 4.0 launched in April 2010 with .NET Framework 4.0, featuring dynamic typing via the dynamic keyword for late binding, named and optional parameters to improve method calls, and support for and contravariance in generics. In August 2012, C# 5.0 debuted with .NET Framework 4.5, primarily introducing the async and await keywords to simplify asynchronous programming without blocking threads. C# 6.0 was released in July 2015 alongside .NET Framework 4.6, incorporating for formatted strings, null-conditional operators (?.) to avoid null reference exceptions, and expression-bodied members for concise property and method definitions. C# 7.0 through 7.3 spanned 2017 to 2018, aligned with .NET Core 1.0 to 2.2 and .NET Framework 4.7 to 4.7.2; key additions included tuples for lightweight data structures, for deconstructing data, local functions for scoped helpers, and enhancements like async entry points and readonly references. C# 8.0 emerged in September 2019 with .NET Core 3.0, enabling to help prevent errors, default methods for evolving , and async streams for asynchronous iteration. Released in November 2020 with .NET 5, C# 9.0 introduced as immutable data types, init-only properties for set-once setters, and top-level statements to reduce boilerplate in simple programs. C# 10.0 followed in November 2021 with .NET 6, offering global using directives for broader namespace imports, file-scoped namespaces to limit scope, and combining value types with records. In November 2022, C# 11.0 accompanied .NET 7, adding raw string literals for multiline strings without escapes, generic attributes for type-parameterized metadata, and required members to enforce initialization. C# 12.0 was released in November 2023 with .NET 8, featuring primary constructors for direct parameter use in classes, collection expressions for concise and initialization, and inline arrays for performance-critical fixed-size buffers. C# 13.0 launched in November 2024 alongside .NET 9, enhancing params collections for flexible array parameters, introducing a new lock type for improved concurrency, and supporting implicit indexer access for easier collection manipulation. The latest version, C# 14.0, was released in November 2025 with .NET 10, introducing extension members for static extensions on interfaces, the field keyword to simplify property implementations, implicit conversions for types, and null-conditional assignments.

Syntax and basic features

Basic syntax elements

C# programs follow a structured format that organizes code into namespaces, classes, and methods. A typical program begins with using directives, which import namespaces to access predefined types and members without fully qualifying their names, such as using System;. Namespaces group related types and prevent naming conflicts, declared with the syntax namespace Identifier { ... }. The core logic resides within a class, defined as class ClassName { ... }, and execution starts from the Main method, which is static and returns void, typically static void Main(string[] args) { ... }. In modern C# versions, top-level statements allow omitting explicit class and Main declarations for simpler console applications. Comments in C# document code without affecting compilation. Single-line comments begin with // and extend to the line's end, as in // This is a comment. Multi-line comments enclose text between /* and */, spanning multiple lines if needed, for example:
csharp
/* This is a multi-line
   comment. */
comments use /// to generate XML-formatted output for tools like IntelliSense. Variables store data during execution and are declared with a type, name, and optional initializer, such as [int](/page/INT) count = 0;. Multiple variables of the same type can be declared comma-separated: [int](/page/INT) a, b;. Constants, declared with const, hold immutable values known at and must be initialized immediately, like const [double](/page/Double) Pi = 3.14159;. Only built-in types such as , floating-point, , and support constants. Operators perform operations on operands. Arithmetic operators include (+), (-), (*), and (/), applied to numeric types; for instance, int sum = 5 + 3; yields 8. Logical operators evaluate expressions: conditional AND (&&) returns true if both operands are true, as in (x > 0) && (y > 0), while conditional OR (||) returns true if at least one is true. The operator (=) stores a value in a , e.g., x = 10;. Strings represent sequences of characters, declared as string message = "Hello";. String literals are enclosed in double quotes and support escape sequences for special characters, such as \n for or \" for quotes inside strings. Verbatim string literals, prefixed with @, treat backslashes literally without processing, useful for paths like @"C:\folder\file.txt". Preprocessor directives control compilation conditionally. The #define directive defines a at the file's top, e.g., #define DEBUG, while #if includes code only if the symbol is defined, paired with #endif, as in:
csharp
#if DEBUG
    Console.WriteLine("Debug mode");
#endif
These directives enable platform-specific or debug code without runtime checks.

Data types and type system

C# features a static, strongly typed that enforces at , ensuring that operations are performed only on compatible types and preventing many common programming errors. All types in C# ultimately derive from the base class System.Object, forming a unified type system that supports both value semantics and reference semantics. The language distinguishes between value types, which store their data directly, and reference types, which store references to their data on the managed heap. This design promotes memory efficiency for small, simple data while allowing complex objects to be shared and garbage-collected. Value types in C# include primitive types such as int (a 32-bit signed integer ranging from -2,147,483,648 to 2,147,483,647), float (a 32-bit single-precision floating-point number with approximately 7 decimal digits of precision), and bool (representing true or false values). User-defined value types encompass struct (composite types that can contain fields, methods, and properties, like a point with x and y coordinates) and enum (sets of named integer constants, such as days of the week with an underlying int type). Variables of value types hold the actual data inline on the stack or within other objects, and assignment creates a copy rather than a shared reference, which ensures isolation but requires explicit copying for large structures. Reference types, in contrast, include class (for defining objects with fields, methods, and support), interface (contracts specifying methods and properties that implementing types must provide), delegate (type-safe function pointers that reference one or more methods), arrays (collections of elements of the same type, deriving from System.Array), and string (immutable sequences of characters, aliasing System.String). These types allocate their instances on the , with variables holding (pointers) to the data; assigning a reference type variable copies the reference, allowing multiple variables to point to the same object and enabling shared modifications. is a valid value for reference types, representing the absence of an object. C# supports through the var keyword, which allows the to deduce the type of a variable from its initializer expression, such as var number = 42; inferring an int. This feature simplifies code without sacrificing , as the inferred type is fixed at and treated equivalently to an explicit declaration. The analyzes the expression's type, preferring more specific types over general ones like object. To enable value types to participate in polymorphic scenarios, C# provides and mechanisms. Boxing implicitly converts a value type instance to a reference type, such as object, by allocating a new object on the and copying the value into it, allowing the value to be treated as an object (e.g., stored in collections). explicitly extracts the value back to its original type via a cast, copying the data from the boxed object, but requires exact type matching to avoid exceptions like InvalidCastException. These conversions incur performance overhead due to heap allocation and copying, so they are used judiciously. The emphasizes safety through compiler-enforced checks, including restrictions on implicit s (e.g., no between bool and integers to prevent logical errors) and support for nullable reference types (introduced in C# 8.0) that generate warnings for potential null dereferences in nullable-enabled contexts. The compiler performs static analysis to detect type mismatches, invalid casts, and unsafe operations at , reducing runtime errors and enhancing code reliability. All types are verifiable under the , ensuring that only safe code executes.

Control structures and statements

C# provides a variety of control structures and statements to manage the flow of program execution, enabling conditional branching, repetition, and abrupt transfers of control. These mechanisms allow developers to implement logic that responds to conditions, iterates over data, and handles errors gracefully, forming the backbone of in the language. All control structures operate on expressions derived from the , such as comparisons between numeric or types.

Conditionals

The if statement evaluates a Boolean expression and executes a statement or block if the condition is true, optionally followed by an else clause for the false case. It supports chaining via else if for multiple conditions, allowing nested decision-making without deep indentation in simple cases. For example:
csharp
if (temperature < 0)
{
    Console.WriteLine("Freezing");
}
else if (temperature < 20)
{
    Console.WriteLine("Cold");
}
else
{
    Console.WriteLine("Warm");
}
This structure ensures only one path executes, promoting clear, linear flow control. The switch statement selects among multiple cases based on matching an expression's value or pattern against labels, executing the corresponding block until a jump statement like break terminates it. Unlike earlier languages, C# prevents fall-through by default, requiring explicit jumps to continue to subsequent cases. Introduced in C# 7.0, enhanced pattern matching allows relational patterns (e.g., case < 0:) and guards with when clauses for complex conditions. An example demonstrates value-based switching:
csharp
switch (day)
{
    case DayOfWeek.Monday:
    case DayOfWeek.Friday:
        Console.WriteLine("Start of workweek");
        break;
    case DayOfWeek.Saturday:
    case DayOfWeek.Sunday:
        Console.WriteLine("Weekend");
        break;
    default:
        Console.WriteLine("Midweek");
        break;
}
Starting in , the switch expression provides a concise alternative for computing values, returning a result rather than executing side effects, as in result = input switch { 1 => "One", _ => "Other" };. This feature integrates seamlessly with assignment and expression-bodied members, reducing verbosity in functional-style code.

Loops

Iteration statements in C# enable repeated execution of code blocks, with variations controlling the entry and exit . The initializes variables, checks a before each , and updates via an expression after the body, ideal for fixed-range counting. Its syntax is for (initializer; [condition](/page/Condition); [iterator](/page/Iterator)) [statement](/page/Statement);, and all parts are optional, allowing flexible use like infinite loops. For instance:
csharp
for (int i = 0; i < 5; i++)
{
    Console.WriteLine(i);
}
This outputs numbers 0 through 4, with the condition preventing execution beyond the bound. The while loop executes its body zero or more times as long as a Boolean condition holds true, evaluating the condition before each iteration to allow early termination. It suits scenarios where the iteration count is unknown upfront, such as processing input until a sentinel value. An example is:
csharp
int count = 0;
while (count < 5)
{
    Console.WriteLine(count);
    count++;
}
In contrast, the do loop guarantees at least one execution by checking the condition after the body, useful for validation prompts or menu systems. Its form is do statement while (condition);, as shown:
csharp
int value = 0;
do
{
    value++;
    Console.WriteLine(value);
} while (value < 5);
The foreach loop iterates over elements in collections implementing IEnumerable or IEnumerable<T>, deconstructing each item without manual indexing, which simplifies or traversal and reduces errors like off-by-one bounds. It throws a NullReferenceException if the collection is null. Example:
csharp
string[] fruits = { "apple", "banana", "cherry" };
foreach (string fruit in fruits)
{
    Console.WriteLine(fruit);
}
This outputs each fruit name sequentially.

Jump Statements

Jump statements alter control flow by transferring execution unconditionally to another point. The break statement exits the nearest enclosing loop (for, while, do, foreach) or switch section, useful for early termination based on a condition. In nested loops, it affects only the innermost one. For example, within a for loop, if (i == 3) break; halts at 3. Similarly, in switch, it prevents unintended fall-through. The continue statement skips the remainder of the current iteration in the nearest loop and proceeds to the next, evaluating the condition or iterator as appropriate. It does not apply to switch and is ideal for filtering iterations, such as ignoring even numbers: if (i % 2 == 0) continue;. In for loops, it jumps directly to the iterator. The return statement terminates the enclosing method or property accessor, optionally returning a value matching the declared type (or void for none). It can include an expression for computation, like return radius * height * Math.PI;, and supports ref returns in modern C# to alias variables without copying. This enables early exits from functions based on validation. The statement jumps to a labeled statement within the same , identified by label:, but is restricted: it cannot enter try blocks or jump over variable initializers, and labels must be unique. Though functional for breaking out of nested loops (e.g., goto done;), its use is discouraged due to reduced , with alternatives like break labels preferred. An example in a switch is goto case 1;, but compile-time errors occur for invalid targets.

Exception Handling Basics

Exception handling in C# uses structured blocks to detect and respond to runtime errors, promoting robust code without halting execution. The try statement encloses potentially faulty code, followed optionally by catch for handling specific and finally for cleanup. If no exception occurs, catch and finally still execute as needed; otherwise, control transfers to the matching catch after unwinding the . Multiple catch blocks can filter by type hierarchy, evaluated in order. A basic form is:
csharp
try
{
    int result = 10 / 0;
}
catch (DivideByZeroException)
{
    Console.WriteLine("Division error");
}
finally
{
    Console.WriteLine("Cleanup");
}
The finally block always runs, even if return or unhandled exceptions occur, ensuring resource disposal like closing files. The throw statement initiates an exception, either creating a new one (e.g., throw new ArgumentException("Invalid");) or re-throwing the current one with just throw;, which preserves the stack trace. This mechanism integrates with the .NET runtime's exception propagation.

Object-oriented programming

Classes and objects

In C#, classes form the cornerstone of , serving as blueprints for creating objects that encapsulate data and behavior. A is declared using the class keyword followed by an optional access modifier and the class name, such as public class MyClass { }. This defines a reference type that can include data members like fields and function members like constructors and methods. Fields in a class are variables that store the state of an object, declared with a type and name, for example, private int _value;. They can be instance fields, which belong to each object, or static fields, shared across all instances. Constructors are special methods invoked during object creation to initialize fields; they share the class name and have no return type, such as public MyClass(int initialValue) { _value = initialValue; }. Since C# 12, primary constructors allow concise declaration like public class MyClass(int value) { }, where the parameter acts as a field. In C# 13, partial properties and indexers enable splitting declaration and implementation across partial classes for better modularity in large projects, such as public partial string Name { get; set; } with a separate implementing partial class. Additionally, since C# 14, the field contextual keyword simplifies access to auto-property backing fields in accessors, e.g., set => field = value ?? throw new ArgumentNullException(nameof(value));, reducing boilerplate without explicit field declarations. Destructors, known as finalizers in C#, are optional cleanup methods prefixed with ~, like ~MyClass() { }, executed by the garbage collector before an object is reclaimed, though their use is discouraged in favor of the IDisposable pattern for resource management. In C# 14, partial constructors allow defining and implementing constructors across partial classes, enhancing separation of concerns. Objects are instances of classes created using the new keyword, which allocates on the managed and invokes the constructor, as in MyClass obj = new MyClass(42);. This process creates a entity based on the definition, allowing multiple objects to exist independently unless explicitly shared. Access modifiers control the visibility of classes and members: [public](/page/Public) allows from any code; [private](/page/Private) restricts to within the same ; protected permits within the class and derived classes; and internal limits access to the same . These modifiers, applied like private int _field;, ensure controlled exposure of class elements. C# distinguishes between instance members, which operate on specific objects (e.g., public int GetValue() { return _value; }), and static members, declared with the static keyword and belonging to the class itself (e.g., public static int Count;), accessed via the class name without . Static members are useful for shared or utility functions not tied to object state. Encapsulation in C# is achieved by bundling data and methods within a class while using access modifiers to hide internal implementation details, exposing only necessary interfaces through public members. This principle promotes data integrity and modularity, as private fields can only be modified via controlled methods or properties, preventing direct external manipulation.

Inheritance and polymorphism

C# supports single inheritance for classes, allowing a derived class to inherit from exactly one class, which promotes by enabling the derived class to access and extend the class's members. This model is transitive, meaning a class can indirectly inherit from multiple ancestors through a chain of derivations. The base keyword is used within a derived class to access constructors, instance members, or static members of the immediate class, facilitating initialization and invocation of base functionality. Method overriding in C# enables derived classes to provide specific implementations of base class methods, enhancing flexibility. To allow overriding, a base class method must be declared with the virtual keyword, indicating it can be replaced in derived classes. A derived class then uses the override keyword to redefine the , ensuring the new implementation is bound at runtime based on the object's actual type. For instance, consider a base Shape with a virtual Draw :
csharp
public class Shape
{
    public virtual void Draw()
    {
        Console.WriteLine("Drawing a shape");
    }
}
A derived class Circle can override it as follows:
csharp
public class Circle : Shape
{
    public override void Draw()
    {
        Console.WriteLine("Drawing a circle");
    }
}
If overriding is not desired but a derived class method shares the same name, the new keyword hides the base method, resolving it at compile time based on the reference type. Polymorphism in C# allows objects of different classes to be treated uniformly through a common class , with behavior determined by the actual object type. Runtime polymorphism, also known as dynamic polymorphism, occurs when virtual or override are invoked; the (CLR) resolves the call to the most derived implementation at execution time. This enables code like treating a collection of Shape references to invoke the appropriate for each derived object, such as Circle or Rectangle. Compile-time polymorphism, in contrast, relies on overloading or the new keyword for name hiding, where the method selected depends on the reference type and parameters at compilation. supports polymorphic usage by converting between and derived types; implicit casting occurs from derived to base, while explicit casting (e.g., (Shape)circle) is required in the reverse direction to access derived-specific members, potentially throwing an InvalidCastException if incompatible. Since , extension members provide an alternative to inheritance for extending existing types, allowing the addition of properties, static members, and operators without modifying the original type or creating derived classes; for example, extending IEnumerable<T> with an IsEmpty property via public static bool IEnumerable<TSource>.IsEmpty(this IEnumerable<TSource> source) => !source.Any();. To prevent unintended inheritance hierarchies, C# provides the sealed keyword, which can be applied to classes or individual members to prohibit further derivation or overriding. A sealed class cannot serve as a base for other classes, promoting design stability in libraries. Abstract classes in C# offer a partial implementation for inheritance, declared with the abstract keyword and unable to be instantiated directly; they may include abstract members that derived classes must override. This mechanism enforces a contract for subclasses while allowing shared code, with further details covered in abstract class usage.

Interfaces and abstract classes

In C#, interfaces provide a mechanism for defining contracts that specify behavior without implementation details, enabling multiple types to share common functionalities and supporting multiple inheritance of type and behavior. An interface is declared using the interface keyword and conventionally prefixed with "I", such as IEnumerable<T>. Members of an interface, including methods, properties, events, and indexers, are implicitly public and abstract by default, requiring implementing classes or structs to provide the necessary implementations. Since C# 13, ref struct types can implement interfaces with restrictions to maintain reference safety, allowing high-performance types like spans to fulfill contracts without heap allocation. Classes and structs can implement interfaces either implicitly or explicitly. Implicit implementation involves declaring public members that match the interface's signatures exactly, allowing access through the class instance itself; for example, a Car class implementing IEquatable<Car> would include a public Equals(Car? other) method. Explicit implementation, on the other hand, prefixes the member with the interface name (e.g., bool IEquatable<Car>.Equals(Car? other)), making it accessible only when the instance is treated as the interface type, which is useful for resolving conflicts or hiding implementation details from the public API. Since C# 8.0, interfaces support default implementations for members, allowing classes and structs to inherit these without overriding, thus providing extensibility for existing types; for instance, an interface method like void Paint() => Console.WriteLine("Default paint"); can be defined directly in the interface. In C# 14, partial events in interfaces can have defining and implementing declarations across partial types. A single class or struct can implement multiple interfaces, facilitating composition of behaviors from diverse sources, though C# prohibits multiple class inheritance to avoid diamond problems. When interfaces share a common base or have overlapping members, explicit implementation resolves ambiguities; for example, a Box class implementing both IEnglishDimensions and IMetricDimensions—each with a Length property—can provide distinct implementations like float IEnglishDimensions.Length => _lengthInches and float IMetricDimensions.Length => _lengthInches * 2.54f, accessed via the respective interface references. This supports polymorphism by allowing a single type to fulfill multiple roles. Abstract classes complement interfaces by offering partial implementations and state, declared with the abstract keyword and serving as non-instantiable base classes for inheritance hierarchies. Unlike interfaces, abstract classes can include concrete members (e.g., implemented methods like public void GetInfo() { ... }), constructors, fields, and protected members, while also declaring abstract members (e.g., public abstract void Move(); or public abstract int MaxSpeed { get; }) that derived classes must override. This allows abstract classes to provide shared functionality—such as common logic in a base Vehicle class—while enforcing specific behaviors in subclasses, differing from interfaces by permitting state and single inheritance only. Covariance and contravariance enhance flexibility in generic interfaces and delegates, enabling implicit conversions that align with type hierarchies. Covariance, denoted by the out keyword (introduced in .NET Framework 4), applies to output positions like return types, allowing a more derived type to be used where a less derived one is expected; for example, IEnumerable<string> can be assigned to IEnumerable<object>. Contravariance, via the in keyword, applies to input positions like parameters, permitting a less derived type where a more derived one is required, such as assigning Action<object> to Action<string>. These features, supported in delegates since C# 2.0 and extended to generic interfaces, promote reusable and type-safe abstractions without runtime overhead. Interfaces and abstract classes are pivotal in that emphasize abstraction and interchangeability, such as the , where an interface defines a family of algorithms (e.g., ISortStrategy with an Execute method), and concrete classes provide implementations that can be injected into a context class for runtime selection. This decouples the client from specific strategies, enhancing maintainability and testing.

Advanced language features

Generics and collections

Generics in C# enable the creation of classes, interfaces, structures, and methods that operate on data types specified as parameters, promoting , , and performance without the need for explicit type casting. Introduced in C# 2.0 as part of the .NET Framework 2.0, generics addressed limitations of earlier non-generic collections by allowing compile-time type checking, reducing and overhead for value types. The syntax for generics uses angle brackets to declare type parameters, typically denoted by a single uppercase letter such as T. For a generic , the declaration follows the form public [class](/page/Class) GenericClass<T> { }, where T serves as a for any type provided at , such as GenericClass<int>. Generic methods are declared similarly within classes, with the type parameter preceding the return type: public T Process<T>(T input) { return input; }. Multiple type parameters are supported, as in public [class](/page/Class) [Dictionary](/page/Dictionary)<TKey, TValue> { }, allowing independent type specifications for different roles. To ensure type parameters meet specific requirements, C# supports constraints via the where clause. Common constraints include where T : [class](/page/Class) to restrict T to types, where T : struct for types, where T : new() to require a parameterless constructor, and where T : SomeInterface or where T : BaseClass to enforce or . These constraints enable access to members like constructors or methods on T within the generic code. For example:
csharp
[public](/page/Public) class Repository<T> where T : [class](/page/Class), new()
{
    [public](/page/Public) T Create() => new T();
}
This ensures T is instantiable and a reference type. C# 13 introduced the allows ref struct anti-constraint, enabling generic types to accept ref struct types like Span<T>. C# provides a rich set of built-in generic collections in the System.Collections.Generic namespace, designed for type-safe storage and manipulation. List<T> implements a dynamic array that grows as needed, supporting indexed access, addition, removal, and sorting operations on elements of type T. Dictionary<TKey, TValue> stores key-value pairs with fast lookups via hashing, where TKey must be unique and hashable. IEnumerable<T> serves as the foundational interface for read-only iteration over sequences of T, enabling foreach loops and integration with other collection types. These collections replaced legacy non-generic alternatives, offering better performance and avoiding runtime errors from type mismatches. Covariance and contravariance, added in C# 4.0, enhance type compatibility by allowing implicit conversions between related types under certain conditions. permits assigning a type with a more derived type argument to one with a less derived argument, marked by the out keyword on interfaces or delegates (e.g., IEnumerable<out T>), which is useful for output-only scenarios like returning sequences. Contravariance does the opposite for input parameters, using the in keyword (e.g., IComparer<in T>), allowing a method expecting a base type to accept a derived type. For instance, IEnumerable<string> can be assigned to IEnumerable<object> due to , while Action<object> can be assigned to Action<string> due to contravariance. These features apply only to reference types and interfaces declared as variant. Subsequent enhancements have built on these foundations; for example, C# 12 introduced collection expressions, allowing concise initialization of collections like List<int> numbers = [1, 2, 3];, which spreads or targets existing generics for improved readability and efficiency. C# 13 added params collections, enabling params parameters to accept collections like Span<T> or IEnumerable<T> directly. C# 14 introduced implicit conversions between arrays and Span<T>/ReadOnlySpan<T>, along with extension members for IEnumerable<T> such as an IsEmpty and static Combine , and support for unbound types in nameof.

Language Integrated Query (LINQ)

Language Integrated Query (LINQ) is a set of technologies integrated into the C# language that provides a unified, declarative approach to querying data from diverse sources, such as in-memory collections, databases, XML documents, and web services. Introduced with C# 3.0 in November 2007 as part of the .NET Framework 3.5, LINQ enables developers to write type-safe queries using familiar SQL-like syntax directly in code, with full compile-time checking and IntelliSense support. This integration treats queries as first-class language constructs, bridging the gap between and data access patterns. LINQ supports multiple providers tailored to different data sources, allowing consistent querying across environments. LINQ to Objects operates on in-memory collections that implement IEnumerable, enabling queries on arrays, lists, and other generic collections. LINQ to XML facilitates manipulation and querying of XML data structures, treating them as object hierarchies. For relational databases, LINQ to SQL translates queries into SQL statements for direct database interaction, while , used with Core, handles more complex object-relational mapping scenarios. The query syntax in LINQ resembles SQL, using keywords to define operations in a readable, declarative manner. A typical query begins with the from to specify the data source and , followed by where for filtering, select for , join for combining sources, and group by for aggregation. For example, developers can filter a collection of objects by a condition, project specific properties, and group results by a key, all within a single expression. Equivalently, offers method syntax through extension methods in the System.Linq namespace, which use expressions for more programmatic control. Common methods include Where() for filtering, Select() for transforming elements, Join() for correlating sequences, and GroupBy() for partitioning data. This syntax compiles to the same as query syntax, allowing seamless mixing of both styles in the same codebase. LINQ queries employ deferred execution, meaning the query is not evaluated until its results are enumerated, such as in a foreach loop or via methods like ToList() or ToArray(). This improves performance by avoiding unnecessary computations. The core interfaces are IEnumerable for local, in-memory queries, where operations compile to delegate-based code, and IQueryable for remote or provider-specific queries, which build expression trees that providers can translate to native query languages like SQL. C# 14 enhances LINQ through extension members, allowing the addition of new instance properties like IsEmpty and static operators such as + for sequence concatenation on IEnumerable<T>.

Asynchronous programming

C#'s asynchronous programming model, known as the Task-based Asynchronous Pattern (TAP), enables developers to write non-blocking code for I/O-bound and CPU-bound operations, improving application responsiveness without traditional threading complexities. Introduced in C# 5.0 with the .NET Framework 4.5, TAP leverages the async and await keywords to simplify asynchronous code, allowing it to read like synchronous code while executing concurrently. This model replaced older patterns like the Asynchronous Programming Model (APM) and Event-based Asynchronous Pattern (EAP), providing a unified approach for representing and composing asynchronous operations. At the core of are the Task and Task<T> types from the System.Threading.Tasks namespace. A Task represents an ongoing asynchronous operation that may complete successfully, fault, or be canceled, without returning a value. In contrast, Task<T> extends this to include a result of type T upon completion, such as Task<string> for an HTTP response body. These types support chaining, cancellation, and error propagation, forming the foundation for scalable concurrent programming in C#. For example, creating a task might involve Task.Run(() => { /* work */ }) to schedule CPU-intensive code on a thread. The async and await keywords facilitate readable asynchronous methods. The async modifier declares a method as asynchronous, permitting the use of await and typically returning a Task or Task<T>. The await operator pauses the method's execution until the awaited task completes, yielding control back to the caller without blocking the thread, then resumes with the task's result. Consider this example for fetching data concurrently:
csharp
public async Task<string> FetchDataAsync()
{
    using var client = new HttpClient();
    return await client.GetStringAsync("https://example.com");
}
This avoids deadlocks common in synchronous calls and scales better for or server applications. For finer control, ConfigureAwait allows specifying whether the continuation after await should capture the current synchronization context, such as the UI thread in WPF or the request context in . Using ConfigureAwait(false) in library code prevents unnecessary context switches and potential deadlocks, as the default true preserves context for thread-affinity needs. Cancellation is handled via CancellationToken, a struct passed to async methods to signal cancellation; tasks can register callbacks or throw OperationCanceledException when checked. A CancellationTokenSource creates and manages tokens, enabling timed or manual cancellation, as in:
csharp
var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
await SomeAsyncOperationAsync(cts.Token);
This ensures resources are freed promptly in long-running operations. Common patterns include Task.WhenAll for awaiting multiple tasks in parallel, which completes when all provided tasks finish or any faults, returning results via Task<T[]> for typed collections. For instance, processing multiple URLs concurrently uses await Task.WhenAll(urls.Select(FetchDataAsync)) to aggregate responses efficiently. Task.Run schedules synchronous code asynchronously on the , ideal for work without I/O, distinguishing it from await on inherently async APIs like file reads. Later versions introduced optimizations like ValueTask and ValueTask<T> in C# 7.0 and .NET Core 2.0, reducing heap allocations for async methods that often complete synchronously by allowing stack-based results. These are awaitable like Task but should not be awaited multiple times, suiting hot-path scenarios such as cached computations. Further enhancements in .NET 5 added pooling for ValueTask to minimize garbage collection in high-throughput async code. C# 13 extended async methods to support ref locals and ref struct types (without crossing await boundaries) and unsafe contexts. Error handling in async code captures exceptions in the task rather than propagating immediately. When an awaited task faults, the exception is rethrown at the await site, allowing standard try-catch blocks to handle it. For multiple tasks, Task.WhenAll aggregates faults into an AggregateException accessible via Task.Exception, enabling selective unwrapping. Unobserved exceptions in non-awaited tasks can crash the process in but are handled more gracefully in .NET Core, emphasizing explicit awaiting for robustness.

Functional programming elements

C# incorporates several functional programming paradigms, enabling developers to write more declarative and composable code. These features, evolving since C# 3.0, include support for higher-order functions, immutability, and pattern-based logic, which facilitate treating functions as first-class citizens and emphasizing pure, side-effect-free operations. Delegates form the foundation for functional elements in C#, serving as type-safe function pointers that reference methods with specific signatures. Introduced in C# 1.0, delegates allow methods to be passed as parameters, enabling callback patterns and event handling. Events, built atop delegates, provide a publisher-subscriber model where classes can notify subscribers of state changes without tight coupling; for instance, the event keyword restricts external access to multicast delegates, ensuring only the declaring class can invoke them. Lambda expressions, added in C# 3.0, extend delegates by allowing concise anonymous functions using the => operator, which separates parameters from the body. Expression lambdas (e.g., x => x * 2) produce read-only expression trees, while statement lambdas (e.g., x => { return x * 2; }) support multi-statement bodies. These simplify code by replacing verbose delegate declarations and are integral to functional composition. Anonymous methods, predating lambdas in C# 2.0 via the delegate keyword, offer similar functionality but with less syntactic sugar. C# 14 allows lambda parameters to use modifiers like ref or out without explicit types, enhancing flexibility in functional code. Higher-order functions in C# leverage generic delegates like Func<T, TResult>, which represents a function taking input of type T and returning TResult, and Action<T>, which denotes a void-returning procedure. Predicates, using Func<T, bool>, test conditions functionally. These types, available since .NET Framework 2.0, allow functions to accept or return other functions, promoting reusability; for example, List<T>.Find uses a Predicate<T> to filter elements declaratively. Immutability is supported through readonly members, which prevent field modification after initialization, and records introduced in C# 9.0. Records are reference types (or value types via record struct) with built-in value equality, immutability via init-only properties, and concise syntax like positional records (e.g., record Point(int X, int Y);). The with expression enables non-destructive updates, creating modified copies without altering originals, aligning with functional principles of persistence. Pattern matching, enhanced starting in C# 7.0, allows declarative and testing of data structures using is and switch expressions. For example, if (obj is Point { X: > 0 } p) binds and tests properties simultaneously, reducing boilerplate in conditional logic. Switch expressions (e.g., shape switch { [Circle](/page/Circle) c => Math.PI * c.Radius * c.Radius, _ => 0 }) provide exhaustive, functional-style dispatching based on type or value patterns. Expression trees represent lambda expressions as inspectable data structures in the System.Linq.Expressions namespace, enabling dynamic code generation and analysis. Compiled from lambdas at runtime, they form trees of nodes like BinaryExpression for operations (e.g., x + y), allowing manipulation for scenarios like query translation. Introduced with .NET 3.5, they underpin functional query composition without immediate execution. C# 14 introduces extension members, enabling the addition of properties, indexers, and static members to existing types like IEnumerable<T>, further supporting functional extensions. These elements, originating prominently in C# 3.0 with expressions and extension methods, have evolved through versions like C# 9.0's and C# 11's refined patterns, fostering a blend of imperative and functional styles. (LINQ) exemplifies their application in declarative manipulation.

Libraries and ecosystem

Standard libraries

The standard libraries in C# are part of the .NET Base Class Library, providing a rich set of reusable types and members for common programming tasks. These libraries are organized into namespaces that offer foundational functionality, enabling developers to perform operations like , manipulation, and concurrency without external dependencies. The namespace serves as the root for fundamental types and utilities in C#. It includes the Console class, which manages standard input and output streams for console applications, allowing methods like WriteLine for displaying text and ReadLine for user input. The Math class provides static methods and constants for common mathematical operations, such as trigonometric functions (Sin, Cos), logarithms, and rounding (Round, Floor). Additionally, DateTime represents instants in time, supporting creation, formatting, and arithmetic like adding intervals or comparing dates. The Random class generates pseudo-random numbers for tasks requiring statistical randomness, using a seed-based algorithm to produce sequences of integers or doubles. The System.IO namespace handles input and output operations, particularly for files and streams. The File class offers static methods for file management, including creating, reading, writing, copying, moving, and deleting files, often returning streams for further processing. Stream is an abstract base class that provides a generic interface for reading and writing sequences of bytes, serving as the foundation for derived classes like FileStream or MemoryStream. The Path class includes utilities for manipulating file paths in a platform-independent manner, such as combining directory and file names (Combine), extracting extensions (GetExtension), or checking validity (IsPathRooted). System.Collections contains interfaces and classes for non-generic collections, which are legacy types still available for but generally superseded by alternatives in modern code. Key examples include ArrayList, a that grows as elements are added; Hashtable, which stores key-value pairs using hash codes for fast lookups; for first-in-first-out operations; and for last-in-first-out behavior. Interfaces like ICollection define basic enumeration and sizing, IDictionary handles key-based access, and IList supports indexed retrieval. The System.Linq namespace provides extension methods essential for (LINQ), enabling declarative querying of data sources. The Enumerable class includes static methods like Where for filtering, Select for projection, and OrderBy for sorting, which extend IEnumerable<T> to support in-memory queries. Queryable offers similar methods for IQueryable<T>, facilitating deferred execution in scenarios like database queries. These methods integrate seamlessly with , using lambda expressions for concise data manipulation. System.Threading supplies basic primitives for multithreaded programming, focusing on synchronization and thread management. The Monitor class enables mutual exclusion with methods like Enter and Exit to protect critical sections from concurrent access. Interlocked performs atomic operations on variables, such as incrementing or exchanging values without race conditions. Other primitives include Mutex for inter-process synchronization, AutoResetEvent for signaling single threads, and ThreadPool for queuing work items to a pool of background threads.

Common Language Infrastructure (CLI)

The (CLI) is an open specification that defines a runtime environment for executing managed written in multiple high-level programming languages, enabling cross-language interoperability and platform portability. Standardized as ECMA-335 by and ISO/IEC 23271, it encompasses the core components necessary for compilation, execution, and management of applications on various operating systems. The CLI serves as the foundation for implementations like the .NET , where is transformed into an intermediate form for just-in-time execution. The Common Type System (CTS), a core partition of the CLI, establishes a unified framework for defining, declaring, and managing types across languages, ensuring consistent behavior and seamless interaction between components developed in different languages. It supports an object-oriented model with categories including reference types (such as classes and interfaces), value types (like structures and enumerations), and primitive types (e.g., Boolean, Int32), all deriving from the base type System.Object to promote inheritance and polymorphism. This type unification allows, for instance, a C# class to be referenced and extended in a Visual Basic .NET application without compatibility issues, as the CTS enforces rules for type safety, visibility (public or private), and layout. Metadata in the CLI provides a language-agnostic, binary description of program elements, including types, members, references, and attributes, embedded directly within assemblies to create self-describing components. Assemblies, manifested as (PE) files in .exe (executable) or .dll (library) formats, bundle this with (IL) code and a detailing , , and . The enables the runtime to resolve dependencies, enforce versioning, and apply security policies, while the tables allow and without requiring external type libraries or registration. Garbage collection in the CLI automates through a mark-and-sweep collector operating on a managed , a dedicated contiguous for allocating and deallocating objects to prevent leaks and fragmentation. The is segmented into a small object heap for objects under 85 and a large object for bigger allocations like arrays, with the collector using generational collection to prioritize efficiency: 0 holds short-lived objects (e.g., temporary variables) for frequent, low-cost collections; survivors promote to 1, an intermediary ; and long-lived objects (e.g., static fields) reside in 2, triggering full collections only when necessary. This approach leverages the observation that most objects die young, minimizing pause times and optimizing throughput in and modes. The CLI's execution model relies on Just-In-Time (JIT) compilation, where language compilers first translate into verifiable, platform-independent Intermediate Language (IL) instructions, stored in assemblies with metadata tokens for reference resolution. During runtime, the compiler converts IL to native optimized for the host CPU, performing optimizations like inlining and while enforcing through to catch errors like invalid casts. This two-stage process balances development productivity with runtime performance, allowing the same assembly to run across architectures via adaptive . The CLI's security model historically included Code Access Security (CAS), a declarative and imperative framework that granted permissions (e.g., file I/O or network access) based on code evidence such as digital signatures or zones, using a stack-walk mechanism to ensure callers had requisite rights and prevent elevation of privilege. However, CAS was deprecated as unsupported legacy technology in .NET Framework post-4.0 due to complexity and security gaps, and in .NET Core and .NET 5+, CAS APIs are obsolete—issuing compile warnings and either ignoring attributes or throwing PlatformNotSupportedException—relying instead on transparent code execution, OS-level isolation, and modern for protection.

Interoperability

C# provides robust interoperability mechanisms that allow seamless integration with unmanaged code, legacy systems, and other programming languages within the .NET ecosystem. These features enable developers to leverage existing native libraries, components, and cross-platform APIs while maintaining the benefits of managed code execution. The (CLI) serves as the foundational enabler for much of this integration by standardizing metadata and execution models across languages. Platform Invoke (P/Invoke) facilitates calling functions, structs, and callbacks from native DLLs in unmanaged code, such as those written in C or C++. Developers declare external methods using the [LibraryImport] attribute to specify the DLL path and marshaling details, ensuring type compatibility between managed and unmanaged environments. For instance, invoking the Windows MessageBoxW function from user32.dll requires defining a partial method signature in C# that matches the native prototype, with automatic marshaling for strings and pointers via IntPtr. This mechanism supports cross-platform scenarios, like calling getpid on Linux from libc.so.6, and includes error handling through Marshal.GetLastPInvokeError. P/Invoke is essential for integrating legacy native libraries without rewriting them. COM interop bridges C# with (COM) components, allowing managed code to consume or expose COM objects. The [ComImport] attribute marks a C# interface or class as an import from a COM type library, enabling direct access to COM functionality without generating interop assemblies manually. When a .NET client invokes a COM object, the runtime creates a Runtime Callable Wrapper (RCW) that abstracts differences in , , and interface querying between the two models. The RCW handles marshaling, lifetime management, and exception translation, ensuring transparent calls from C# to COM. Conversely, COM Callable Wrappers (CCWs) allow COM clients to interact with .NET objects. This setup supports legacy Windows applications, such as , by qualifying types for interoperation. Within the .NET ecosystem, C# exhibits strong cross-language , permitting code written in C# to directly call and inherit from components in other .NET languages like VB.NET or F#. This is achieved by compiling modules from different languages into a shared , where ensures type compatibility and resolution. For example, a C# application can reference a VB.NET class library containing string utilities and invoke its methods without language-specific barriers, as all compile to (IL). Similarly, F# functional constructs can be consumed in C# projects, fostering mixed-language development in unified solutions. This language independence promotes across the .NET platform. .NET Standard enhances multi-platform compatibility by defining a common set of APIs that C# libraries can target, ensuring they work across diverse .NET implementations like .NET Framework, .NET Core, and Xamarin. Libraries built against .NET Standard 2.0, which includes over 32,000 APIs, can be consumed by applications on Windows, macOS, Linux, and mobile platforms without modification. This specification acts as a contract for interoperability, allowing a single C# library to support both legacy .NET Framework desktop apps and modern cross-platform .NET 8+ runtimes. Targeting .NET Standard is recommended for shared libraries to maximize portability. Blazor, leveraging WebAssembly, enables C# code to run in web browsers and interoperate directly with JavaScript and browser APIs. Through JavaScript interop, C# methods can invoke JS functions via the IJSRuntime interface, passing parameters asynchronously and handling results with JSON serialization. For example, a Blazor component might call a JS function to access the browser's geolocation API, while JS can invoke exported .NET methods using [JSExport]. This bidirectional integration, optimized for performance with unmarshaled calls, allows full-stack C# development for web UIs without relying solely on JavaScript. WebAssembly execution ensures C# runs natively in the browser sandbox.

Implementations and tools

Microsoft implementations

Microsoft's implementations of C# are centered around the .NET platform, which provides the runtime, libraries, and compiler infrastructure necessary for developing and executing C# applications. The primary compiler is Roslyn, an open-source .NET Compiler Platform that handles parsing, semantic analysis, and code generation for C# and Visual Basic. Roslyn was first released as open-source under the Apache 2.0 license on April 3, 2014, enabling developers to build custom tools, analyzers, and extensions directly on top of the compiler APIs. It powers the C# compilation in Visual Studio and the .NET CLI, supporting incremental compilation for improved performance in large projects. The foundational runtime for early C# implementations was the .NET Framework, a Windows-specific platform that evolved from version 1.0, released in February 2002, to version 4.8 in April 2019. .NET Framework 1.0 introduced the (CLR) version 1.0, enabling managed code execution with garbage collection and . Key subsequent releases included .NET Framework 2.0 (November 2005, CLR 2.0 with generics support), 3.5 (November 2007, adding ), 4.0 (April 2010, CLR 4.0 with dynamic typing), and up to 4.8, which incorporated security enhancements and accessibility improvements while maintaining . The .NET Framework remains supported for legacy Windows applications but is no longer receiving major feature updates. To address cross-platform needs, launched .NET Core in June 2016 as a modular, open-source , starting with version 1.0 and progressing through 3.1 (December 2019, the last release before unification). .NET Core emphasized performance optimizations, such as the RyuJIT , and supported , macOS, and Windows. In November 2020, .NET 5 marked the unification of .NET Framework and .NET Core into a single cross-platform platform, eliminating divergence in APIs and tools; this continued with annual releases like .NET 6 (November 2021, with improved container support), .NET 7 (November 2022), and .NET 8 (November 2023). The unified .NET platform now uses a single codebase, with .NET Standard libraries ensuring compatibility across implementations. For compatibility with existing codebases, modern .NET includes layers derived from the Mono project, an open-source .NET implementation originally developed by . Following Microsoft's acquisition of in 2016, Mono's runtime was integrated into .NET for non-Windows scenarios, particularly to handle platform-specific behaviors in mobile and embedded environments. This ensures that .NET applications can run legacy Mono-compatible code without modification, leveraging Mono's class libraries for features like on . Microsoft's mobile and desktop development has been advanced through , a C#-based framework for cross-platform apps, and its successor .NET Multi-platform App UI (). Xamarin, released in 2011 and fully integrated into .NET by 2016, allowed shared C# code for , , and Windows apps using native UI controls. Support for Xamarin ended on May 1, 2024, with migration paths to .NET MAUI, introduced in .NET 6 (May 2022), which unifies Xamarin.Forms, Xamarin.Essentials, and WPF/WinUI into a single framework for building native apps across , , macOS, Windows, and from a shared C# codebase. .NET MAUI leverages the unified .NET runtime for deployment, with tools like the .NET Upgrade Assistant facilitating transitions from Xamarin projects. As of November 2025, the latest implementation is .NET 10, released on November 11, 2025, which natively supports features such as improved , extension members, and file-based application structures. .NET 10 builds on the unified platform with runtime improvements, including performance enhancements for cloud-native scenarios, while maintaining full compatibility with prior C# versions.

Alternative implementations

Alternative implementations of C# extend the language's reach beyond Microsoft's proprietary ecosystem, emphasizing open-source, cross-platform, and specialized runtimes and compilers that adhere to ECMA standards for the (CLI). These efforts enable C# development on non-Windows platforms, in game engines, and through community-driven tools, often providing full or partial compatibility with .NET libraries. The Mono project, initiated in 2001 by , represents a pioneering open-source implementation of the .NET Framework, designed specifically for , macOS, and other systems. It includes a complete runtime environment with just-in-time () and ahead-of-time (AOT) compilers, a garbage collector, and class libraries that mirror Microsoft's offerings, such as and , while adding platform-specific extensions like Gtk+ for graphical interfaces. Mono supports C# versions from 1.0 up to 6.0 and has been instrumental in cross-platform applications, including mobile development via , which was later integrated into Microsoft's ecosystem. Originally sponsored by and then , Mono transitioned under the .NET Foundation in 2016, fostering a vibrant that ensures binary compatibility with Microsoft APIs on diverse architectures like x86 and . Its modular design allows developers to build , desktop, and embedded applications without relying on Windows, significantly broadening C#'s adoption in open-source environments. CoreCLR serves as the foundational open-source runtime for .NET Core, released by in 2015 to support modular, cross-platform C# applications. Comprising approximately 2.6 million lines of in C# and C++, it includes the RyuJIT , a high-performance garbage collector, and native interop layers, enabling execution on Windows, , and macOS. Unlike full .NET Framework implementations, CoreCLR focuses on lightweight, container-friendly scenarios such as cloud services and , with initial support following its open-sourcing on under the . This runtime powers .NET Core's ability to run C# in serverless environments and has been extended by the for systems, emphasizing portability and optimizations like tiered compilation. Historically, the DotGNU Portable.NET project, launched in 2001 as part of the GNU initiative, aimed to create a fully free software alternative to Microsoft's .NET for CLI-compliant applications. It featured the cscc compiler, a modular tool written in C that supported C# (ECMA-334 compliant) alongside C, with partial handling for Java and VB.NET through the Tree Compiler Compiler (treecc) framework. The runtime, ilrun, interpreted Common Intermediate Language (CIL) bytecode using a Converted Virtual Machine (CVM) and supported native code generation on platforms like x86, ARM, PowerPC, and Sparc across GNU/Linux, Windows, macOS, and BSD variants. Portable.NET also implemented System.Windows.Forms in pure C# for cross-platform GUIs, but development ceased around 2008, leaving it as a foundational yet decommissioned effort that influenced later open-source .NET tools. In specialized domains like game development, Unity's IL2CPP provides an alternative scripting backend for C# by converting Microsoft Intermediate Language (MSIL) from C# scripts into C++ code, which is then compiled into native binaries for deployment. Introduced to replace Mono's JIT-based approach, IL2CPP enables ahead-of-time (AOT) , enhancing and on platforms prohibiting runtime code generation, such as and consoles. The process involves Roslyn compiling C# to DLLs, followed by managed code stripping for size reduction and IL2CPP's translation to C++, resulting in faster execution and smaller binaries compared to interpreted alternatives, though at the cost of longer build times. Widely adopted in Unity's , IL2CPP supports debugging akin to Mono and targets diverse ecosystems, including and , making C# viable for high-performance interactive applications. Community-driven compilers offer further alternatives to Microsoft's csc (part of Roslyn), with Mono's mcs standing out as an early open-source C# written in C# itself. Developed alongside the Mono , mcs provided full support for C# up to version 6.0, including features like generics and , and was optimized for cross-platform builds on and macOS. It served as the default compiler in Mono distributions until version 5.0 in 2017, when it was largely superseded by Roslyn for ongoing maintenance, though legacy support persists in certain embedded scenarios. Similarly, DotGNU's cscc emphasized modularity and multi-language integration, compiling C# to CIL with strong ECMA compliance, but its historical status limits modern use. These compilers highlight community efforts to decouple C# compilation from proprietary tools, enabling independent experimentation and portability.

Development tools

Visual Studio serves as the primary (IDE) for C# development, offering editions tailored to different user needs. The edition provides free access for individual developers, students, and open-source projects, including core features like code editing and . Professional and editions add advanced capabilities such as architecture tools, live dependency validation, and enhanced testing for larger teams and enterprises. Key features in Visual Studio include IntelliSense, which offers context-aware code completion, parameter information, and quick info tooltips to accelerate coding in C#. Debugging tools enable setting breakpoints, stepping through code, inspecting variables via DataTips, and evaluating expressions in the Immediate Window during execution. These features integrate seamlessly with the Roslyn compiler for real-time error detection and refactoring. Visual Studio Code (VS Code), a lightweight cross-platform editor, supports C# through the official C# Dev Kit extension, which leverages OmniSharp as the language server for features like , , and error squiggles. This setup allows developers to build, run, and debug C# applications on Windows, macOS, and without the full installation. For command-line workflows, the C# compiler (csc.exe) compiles source files into assemblies, supporting options for optimization, debugging symbols, and target outputs like executables or libraries. The .NET CLI (dotnet) complements this by providing commands such as dotnet build, dotnet run, and dotnet test for managing projects, dependencies, and execution across platforms. JetBrains Rider offers a cross-platform alternative IDE with intelligent code analysis, including over 2,200 inspections and 1,000 quick-fixes for C#, alongside navigation tools, decompilation, and unit testing support. It emphasizes productivity through features like whole-line code completions and seamless integration with .NET ecosystems. C# development tools integrate well with testing frameworks like and . In , the Test Explorer discovers, runs, and debugs tests from these frameworks via packages, providing analysis and live unit test results. Similar integration exists in VS Code and , enabling automated test execution within the .

Standardization and adoption

ECMA and ISO standards

C# was initially developed by Microsoft as part of the .NET Framework, with standardization efforts beginning in September 2000 through Ecma International's Technical Committee 39 (TC39, later renamed TC49) Task Group 2 (TG2). The first edition of the C# language specification, ECMA-334, was adopted by the Ecma General Assembly in December 2002, defining the syntax, semantics, and constraints for C# programs. This ECMA standard was fast-tracked for adoption by the (ISO) and the (IEC), resulting in ISO/IEC 23270:2003, which is technically equivalent to ECMA-334 and serves as the international standard for the . Subsequent editions, up to the third edition (ISO/IEC 23270:2018), maintained equivalence with corresponding ECMA revisions up to that point. However, while ECMA-334 has continued to evolve, the ISO standard has not been updated since 2018; and continue to submit revisions for fast-track ISO adoption, but as of November 2025, the ISO remains aligned with earlier C# versions. The C# specifications are provided as open standards under royalty-free licensing terms, allowing any party to freely implement the language without encumbrances, as affirmed by Microsoft's Community Promise and Ecma's policies. The latest edition, ECMA-334 7th edition (December 2023), supersedes the 2022 version and includes updates for features introduced up to C# 12, such as primary constructors. Ongoing standardization ensures compliance with newer language versions; for instance, features from C# 13 (e.g., params collections) and (e.g., enhanced ) are incorporated into future editions through TC49's revision process to reflect the evolving specification.

Usage and popularity

C# is predominantly utilized in the development of Windows and .NET-based desktop applications, web applications via , game development through engines like , and mobile applications using frameworks such as and . In terms of popularity, C# consistently ranks among the top programming languages in major indices. As of November 2025, it holds the fifth position in the with a 7.65% rating, reflecting its strong community interest and search volume. The 2025 Developer Survey reports C# as the eighth most commonly used language, with 27.8% of respondents employing it, particularly in .NET development and contexts. Enterprise adoption of C# remains robust within the ecosystem, where it dominates for building scalable applications integrated with cloud services. In 2025, the growing demand for C# developers in and globally stems from widespread and .NET adoption, enabling efficient cloud-native solutions for businesses. The language has seen significant growth in cross-platform capabilities since .NET 5, allowing developers to build and deploy applications across Windows, , and macOS environments. This evolution, building on .NET Core's open-source foundation, has expanded C#'s reach beyond Windows-centric development, supporting unified platforms for web, desktop, and mobile in 2025. Emerging trends in 2025 highlight C#'s increasing integration with and , facilitated by tools like and AI services, which enable .NET developers to incorporate intelligent features such as and automation directly into applications. Frameworks like allow seamless AI model training and deployment within C# ecosystems, positioning the language as a viable option for AI-driven enterprise solutions. A common criticism of C# has been its historical platform dependency on Windows, which limited portability in earlier .NET Framework versions. However, .NET Core and subsequent releases have mitigated this by introducing cross-platform support from the ground up, enabling deployment on non-Windows operating systems and reducing concerns.

Examples

Hello World program

The "Hello World" program serves as the canonical introductory example in C#, demonstrating the language's fundamental syntax and execution flow. It outputs the text "Hello World" to the console, illustrating how a minimal C# application is structured and run. This example highlights essential elements such as namespaces, classes, and the method, providing a foundation for understanding more complex programs. A basic "Hello World" program in C# is written as follows:
csharp
using [System](/page/System);

[class](/page/Class) [Program](/page/Program)
{
    static void [Main](/page/Method)()
    {
        [Console](/page/System).WriteLine("[Hello World](/page/Hello_World)");
    }
}
This code begins with a using directive that imports the System namespace, granting access to core classes like Console without fully qualifying their names. The program defines a class named Program, which encapsulates the Main method—this static method serves as the application's , invoked automatically when the program starts. Inside Main, the Console.WriteLine method from the System namespace prints the string "Hello World" followed by a to the standard output stream. To compile and execute this program, developers typically use the C# compiler (csc.exe) provided by the .NET SDK. First, save the code in a file with a .cs extension, such as HelloWorld.cs. From the command line, run csc HelloWorld.cs to generate an executable assembly (e.g., HelloWorld.exe on Windows). Then, execute it with HelloWorld.exe, which will display "Hello World" in the console. Alternatively, integrated development environments (IDEs) like Visual Studio automate these steps, handling compilation, linking to the .NET runtime, and launching the application. The program relies on the Common Language Runtime (CLR) for execution, where the just-in-time (JIT) compiler translates the intermediate language (IL) code into machine instructions. Starting with C# 9, introduced in .NET 5, a simplified variant using top-level statements eliminates the need for explicit and method declarations, making the code more concise for simple programs. This version appears as:
csharp
Console.WriteLine("Hello World");
Implicitly, the wraps this in a Main method within a generated , preserving compatibility with the while reducing boilerplate. This feature streamlines scripting and educational examples but is not intended for larger applications.

Generic example

Generics in C# enable the creation of reusable that maintain at , allowing developers to define like Stack<T> that work with any specified type T without sacrificing performance or introducing runtime errors. The following example illustrates a simple implementation of a generic Stack<T> , which represents a last-in, first-out (LIFO) . This uses an to store elements and includes basic Push and Pop methods, with a type constraint where T : IComparable<T> to ensure elements can be compared, enabling potential extensions like sorting while enforcing checks.
csharp
using System;
using System.Collections.Generic;

public class Stack<T> where T : IComparable<T>
{
    private T[] items;
    private int top;

    public Stack(int capacity)
    {
        items = new T[capacity];
        top = 0;
    }

    public void Push(T item)
    {
        if (top == items.Length)
        {
            throw new InvalidOperationException("Stack overflow");
        }
        items[top++] = item;
    }

    public T Pop()
    {
        if (top == 0)
        {
            throw new InvalidOperationException("Stack underflow");
        }
        return items[--top];
    }

    public int Count => top;
}
This implementation demonstrates how generics parameterize the class with T, restricting it to types that implement IComparable<T> for comparability, which provides type-safe access to comparison methods without casting. To use the Stack<T> class, instantiate it with a specific type, such as int for integers, which satisfies the constraint since int implements IComparable<int>. For example:
csharp
Stack<int> intStack = new Stack<int>(5);
intStack.Push(1);
intStack.Push(2);
int value = intStack.Pop();  // Returns 2, type-safe without casting
Console.WriteLine(value);    // Output: 2
This usage highlights the compile-time type safety of generics: the compiler ensures that only int values can be pushed or popped, preventing invalid type assignments that would otherwise occur at runtime. Additionally, for value types like int, generics avoid boxing and unboxing operations, as the internal array stores T directly rather than as object, leading to better memory efficiency and performance compared to non-generic alternatives. In contrast, the non-generic ArrayList from the System.Collections namespace stores elements as object, requiring explicit for retrieval and risking InvalidCastException at if types mismatch. For instance, using ArrayList to simulate a would involve code like:
csharp
using System.Collections;

ArrayList arrayList = new ArrayList();
arrayList.Add(1);  // Boxes int to object
arrayList.Add(2);
int value = (int)arrayList[arrayList.Count - 1];  // Pops via index, requires [unboxing](/page/Unboxing) and casting
This approach incurs boxing overhead for value types, converting them to object on addition and unboxing on retrieval, which degrades performance and lacks the compile-time guarantees of generics. The Stack<T> class, by leveraging generics, eliminates these issues, making it preferable for type-safe, efficient reusable code.

LINQ example

LINQ (Language Integrated Query) provides a declarative way to query and manipulate data collections in C#, using either method syntax with extension methods or query syntax that resembles SQL. A simple example involves filtering even numbers from a list and doubling them, demonstrating how LINQ transforms data without explicit loops. Consider a list of integers:
csharp
List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6 };
Using method syntax, the query can be written as:
csharp
var doubledEvens = numbers.Where(n => n % 2 == 0).Select(n => n * 2);
This employs lambda expressions to define the filtering (even numbers) and (doubling) operations, leveraging the Where and Select standard query operators from the System.Linq namespace. Equivalently, in query syntax:
csharp
var doubledEvens = from n in numbers
                   where n % 2 == 0
                   select n * 2;
This form offers a more readable, SQL-like structure for complex queries while compiling to the same method calls under the hood. LINQ queries exhibit deferred execution, meaning the operations are not performed until the results are enumerated, such as in a foreach loop or when materializing the query into a concrete collection. For instance, calling doubledEvens.ToList() forces immediate execution and returns a List<int> containing {4, 8, 12} in this case. Beyond basic collections, integrates seamlessly with object-oriented data models, allowing queries on classes like Student or Product via , and supports XML through LINQ to XML for loading, querying, and transforming documents declaratively.

References

  1. [1]
    Introduction - C# language specification - Microsoft Learn
    The principal inventors of this language were Anders Hejlsberg, Scott Wiltamuth, and Peter Golde. ... C# is intended to be a simple, modern, general-purpose, ...
  2. [2]
    The history of C# | Microsoft Learn
    This article provides a history of each major release of the C# language. The C# team is continuing to innovate and add new features.What's new in C# 11 · Relationships between... · Local functions
  3. [3]
    What's new in C# 14 - Microsoft Learn
    C# 14 includes the following new features. You can try these features using the latest Visual Studio 2022 version or the .NET 10 SDK.
  4. [4]
    Overview - A tour of C# | Microsoft Learn
    C# is a cross-platform general purpose language that makes developers productive while writing highly performant code.
  5. [5]
    C# - a modern, open-source programming language | .NET
    C# is the modern, open-source, cross-platform object-oriented programming language for the .NET developer platform with free tools for Linux, macOS, ...
  6. [6]
    Anders Hejlsberg: A Craftsman of Computer Language - Microsoft
    Anders has had a 35-year career building tools that software developers love. He built Turbo Pascal, served as chief architect of Delphi, moved to Microsoft to ...
  7. [7]
    Anders Hejlsberg: Geek of the Week - Simple Talk - Redgate Software
    Mar 19, 2009 · Anders Hejlsberg, the creative genius behind C#, and much of the ... “Yes, the codename for C# was COOL, which stood for C-style Object ...
  8. [8]
    Microsoft Introduces Highly Productive .NET Programming Language
    Microsoft Corp. today announced Microsoft® C # ( “C sharp” ), a modern, object-oriented programming language ...
  9. [9]
  10. [10]
    How was C# presented by Microsoft back in 2000? How ... - Reddit
    Oct 13, 2021 · I was present at the session of the Microsoft PDC when C# was announced and first demonstrated to attending programmers by Anders. All ...When exactly C# was firstly introduced? : r/csharp - RedditC# History: How Microsoft Revolutionized Programming with .NETMore results from www.reddit.com
  11. [11]
    [PDF] C# Language Specification - Ecma International
    ... 2002. Standardizing Information and Communication Systems. C# Language ... early programs and the reading of later chapters. 8.1 Getting started. The canonical ...Missing: challenges | Show results with:challenges
  12. [12]
    General Structure of a Program - C# | Microsoft Learn
    Learn about the structure of a C# program by using a skeleton program that contains all the required elements for a program.Basic concepts · Main() and command-line... · Introduction to classes
  13. [13]
    // and /* */ - comments - C# reference | Microsoft Learn
    Dec 13, 2022 · In C#, single-line comments start with `//` and end at the end of the line. Multi-line comments start with `/*` and end with `*/`. Triple-slash ...Missing: syntax | Show results with:syntax
  14. [14]
    Declaration statements - C# reference - Microsoft Learn
    Jun 21, 2023 · A declaration statement declares a new local variable, local constant, or local reference variable. To declare a local variable, specify its type and provide ...
  15. [15]
    Constants - C# - Microsoft Learn
    Mar 12, 2024 · Constants in C# are compile-time literal values, which do not change once the program is compiled. Only C# built-in types can be constants.
  16. [16]
    Arithmetic operators - C# reference - Microsoft Learn
    Jun 11, 2025 · Learn about C# operators that perform multiplication, division, remainder, addition, and subtraction operations with numeric types.Missing: logical | Show results with:logical
  17. [17]
    Boolean logical operators - AND, OR, NOT, XOR - Microsoft Learn
    The operators include the unary logical negation ( ! ), binary logical AND ( & ), OR ( | ), and exclusive OR ( ^ ), and the binary conditional logical AND ( && ) ...Logical And Operator & · Logical Or Operator | · Nullable Boolean Logical...Missing: arithmetic | Show results with:arithmetic
  18. [18]
    assign an expression to a variable - C# reference - Microsoft Learn
    Jun 13, 2025 · The assignment operator = assigns the value of its right-hand operand to a variable, a property, or an indexer element given by its left-hand operand.
  19. [19]
    Strings - C# | Microsoft Learn
    To interpret escape sequences literally, use a verbatim string literal. An interpolated verbatim string starts with the $ character followed by the @ character.
  20. [20]
    Verbatim text and strings - @ - C# reference - Microsoft Learn
    Mar 21, 2023 · The @ character in this instance defines a verbatim string literal. Simple escape sequences (such as "\\" for a backslash), hexadecimal escape ...
  21. [21]
    Preprocessor directives - C# reference - Microsoft Learn
    #if , along with the #else , #elif , #endif , #define , and #undef directives, lets you include or exclude code based on the existence of one or more symbols.
  22. [22]
    Learn the fundamentals of the C# type system
    Learn about creating types in C#, such as tuples, records, value types, and reference types. Learn to choose between these options.Anonymous Types · Casting and type conversions · Record types
  23. [23]
    Types - C# language specification - Microsoft Learn
    Sep 12, 2025 · The types of the C# language are divided into two main categories: reference type and value type. A value type or a reference type may be a ...
  24. [24]
    Built-in types - C# reference - Microsoft Learn
    Aug 5, 2025 · The C# language includes specialized rules for the System. Span<T> and System. ReadOnlySpan<T> types. These types aren't classified as built-in ...Integral numeric types · Value types · Bool · Char
  25. [25]
    Value types - C# reference - Microsoft Learn
    Oct 25, 2024 · Value types and reference types are the two main categories of C# types. A variable of a value type contains an instance of the type.
  26. [26]
    Boxing and Unboxing - C#
    ### Summary of Boxing and Unboxing in C#
  27. [27]
    if and switch statements - select a code path to execute - C# reference
    The `if` and `switch` statements provide branching logic in C#. You use `if, `else` and `switch` to choose the path your program follows.Microsoft Ignite · Jump statements - break... · Switch expression
  28. [28]
    Iteration statements -for, foreach, do, and while - C# reference
    Nov 14, 2023 · The iteration statements repeatedly execute a statement or a block of statements. The for statement executes its body while a specified Boolean expression ...<|control11|><|separator|>
  29. [29]
    Jump statements - break, continue, return, and goto - C# reference
    Mar 14, 2023 · C# jump statements (break, continue, return, and goto) unconditionally transfer control from the current location to a different statement.The break statement · The continue statement
  30. [30]
    Exception-handling statements - throw and try, catch, finally - C# ...
    Use the throw statement to throw an exception. Use the try statement to catch and handle exceptions that might occur during execution of a code block.The Throw Statement · The Try Statement · The Try-Catch Statement
  31. [31]
    Classes in the C# type system. - Microsoft Learn
    A class defines a type of object, but it isn't an object itself. An object is a concrete entity based on a class, and is sometimes referred to as an instance ...Reference types · Declaring classes
  32. [32]
    Classes - C# language specification - Microsoft Learn
    Sep 12, 2025 · A class is a data structure that may contain data members (constants and fields), function members (methods, properties, events, indexers, operators, instance ...
  33. [33]
    Objects - create instances of types - C# | Microsoft Learn
    C# uses a class or struct definition to define types of objects. In an object-oriented language such as C#, a program consists of objects interacting ...
  34. [34]
    Objected oriented programming - inheritance - C#
    ### Summary of C# Class Inheritance (Microsoft Documentation)
  35. [35]
  36. [36]
    Polymorphism - C#
    ### Summary of Polymorphism in C#
  37. [37]
  38. [38]
  39. [39]
    abstract keyword - C# reference - Microsoft Learn
    Aug 20, 2025 · This allows abstract classes to provide common functionality while still requiring derived classes to implement specific abstract members.Missing: patterns | Show results with:patterns
  40. [40]
    Interfaces - define behavior for multiple types - C# | Microsoft Learn
    Oct 13, 2025 · When interfaces declare a default implementation of a method, any class implementing that interface inherits that implementation (You need to ...
  41. [41]
    Explicit Interface Implementation - C# - Microsoft Learn
    Sep 29, 2022 · The following sample defines a default implementation for an interface method: C# Copy. public interface IControl { void Paint() => Console.
  42. [42]
    How to explicitly implement members of two interfaces - C#
    Mar 12, 2024 · Learn how to explicitly implement two interfaces that have the same member names and give each interface member a separate implementation in ...
  43. [43]
    Covariance and Contravariance (C#) - Microsoft Learn
    Jul 30, 2022 · In C#, covariance and contravariance enable implicit reference conversion for array types, delegate types, and generic type arguments.Creating Variant Generic... · Using Variance in Delegates
  44. [44]
    Creating Variant Generic Interfaces (C#) - Microsoft Learn
    Sep 15, 2021 · You can declare generic type parameters in interfaces as covariant or contravariant. Covariance allows interface methods to have more derived return types.
  45. [45]
    Design Patterns: Solidify Your C# Application Architecture with ...
    This article describes several popular design patterns you can use in your own applications, including the singleton, the decorator, the composite, and the ...
  46. [46]
    Generic classes and methods - C# | Microsoft Learn
    Generics overview · Use generic types to maximize code reuse, type safety, and performance. · The most common use of generics is to create collection classes.
  47. [47]
    Generic methods (C# programming guide) - Microsoft Learn
    Mar 27, 2024 · Learn about methods declared with type parameters, known as generic methods. See code examples and view additional available resources.
  48. [48]
    Generic Classes (C# Programming Guide) - Microsoft Learn
    Jul 9, 2022 · Generic classes encapsulate operations that are not specific to a particular data type. The most common use for generic classes is with collections.
  49. [49]
    where (generic type constraint) - C# reference - Microsoft Learn
    Jul 30, 2024 · The where clause in a generic definition specifies constraints on the types that are used as arguments for type parameters in a generic type, method, delegate, ...
  50. [50]
    System.Collections.Generic Namespace - Microsoft Learn
    Contains interfaces and classes that define generic collections, which allow users to create strongly typed collections that provide better type safety and ...
  51. [51]
  52. [52]
  53. [53]
    IEnumerable<T> Interface (System.Collections.Generic)
    Examples. The following example demonstrates how to implement the IEnumerable<T> interface and how to use that implementation to create a LINQ query. When you ...<|control11|><|separator|>
  54. [54]
    Covariance and Contravariance in Generics - .NET - Microsoft Learn
    A generic interface or generic delegate type can have both covariant and contravariant type parameters. Variance applies only to reference types; if you specify ...
  55. [55]
    out keyword (generic modifier) - C# reference - Microsoft Learn
    Sep 15, 2021 · The out keyword specifies that the type parameter is covariant. You can use the out keyword in generic interfaces and delegates.
  56. [56]
    in (Generic Modifier) - C# reference - Microsoft Learn
    A type can be declared contravariant in a generic interface or delegate only if it defines the type of a method's parameters and not of a method's return type.
  57. [57]
    What's new in C# 12 - Microsoft Learn
    Jun 4, 2024 · C# 12 includes the following new features. You can try these features using the latest Visual Studio 2022 version or the .NET 8 SDK.Missing: history | Show results with:history
  58. [58]
    Language Integrated Query (LINQ) - C# | Microsoft Learn
    Language-Integrated Query (LINQ) is the name for a set of technologies based on the integration of query capabilities directly into the C# language.Introduction to LINQ Queries - C · Write LINQ queries · Query expression basics
  59. [59]
    LINQ overview - .NET - Microsoft Learn
    Language-Integrated Query (LINQ) provides language-level querying capabilities, and a higher-order function API to C# and Visual BasicLanguage-level query syntax · LINQ is expressive
  60. [60]
    Query expression basics (LINQ) - C# | Microsoft Learn
    Jan 16, 2025 · This article introduces the basic concepts related to query expressions in C#. What is a query and what does it do? A query is a set of ...
  61. [61]
    Task-based Asynchronous Pattern (TAP): Introduction and overview
    Introduces the three patterns for performing asynchronous operations: the Task-based Asynchronous Pattern (TAP), the Asynchronous Programming Model (APM), and ...
  62. [62]
    Asynchronous programming - C# | Microsoft Learn
    Jul 16, 2025 · The goal of task asynchronous programming is to enable code that reads like a sequence of statements, but executes in a more complicated order.Task asynchronous · Async return types · 15 Classes
  63. [63]
    The Task Asynchronous Programming (TAP) model with async and ...
    Learn when and how to use Task-based async programming, a simplified approach to asynchronous programming in C#.
  64. [64]
    Asynchronous programming scenarios - C# - Microsoft Learn
    The async keyword declares a method as an asynchronous method, which allows you to use the await keyword in the method body. When you apply the await keyword, ...Task asynchronous · Task-based Asynchronous · Async (C# Reference)
  65. [65]
    await operator - asynchronously wait for a task to complete
    Jul 1, 2024 · The await operator suspends evaluation of the enclosing async method until the asynchronous operation represented by its operand completes.
  66. [66]
    Task.ConfigureAwait Method (System.Threading.Tasks)
    When an asynchronous method awaits a Task directly, continuation usually occurs in the same thread that created the task, depending on the async context.
  67. [67]
    Cancel async tasks after a period of time" - C# - Microsoft Learn
    Sep 8, 2023 · You can cancel an asynchronous operation after a period of time by using the CancellationTokenSource.CancelAfter method if you don't want to wait for the ...Prerequisites · Update application entry point
  68. [68]
    Cancel a list of tasks - C# | Microsoft Learn
    You can cancel many tasks by associating the CancellationTokenSource instance with each task. If you select the Enter key, you cancel all tasks that aren't yet ...Prerequisites · Add fields
  69. [69]
    Task.WhenAll Method (System.Threading.Tasks) - Microsoft Learn
    WhenAll(IEnumerable<Task>). Creates a task that will complete when all of the Task objects in an enumerable collection have completed.
  70. [70]
    Understanding the Whys, Whats, and Whens of ValueTask - .NET Blog
    Nov 7, 2018 · But with the .NET Framework 4.5 and C# 5, Task s could simply be await ed, making it easy to consume the results of an asynchronous operation ...Missing: improvements | Show results with:improvements
  71. [71]
    Async ValueTask Pooling in .NET 5 - Microsoft Developer Blogs
    Mar 16, 2020 · The async/await feature in C# has revolutionized how developers targeting .NET write asynchronous code. Sprinkle some async and await around ...
  72. [72]
    Work with delegate types in C# - C# | Microsoft Learn
    Mar 13, 2025 · Explore delegate types in C#. A delegate is a date type that refers to a method with a defined parameter list and return type.Using Delegates · How to declare, instantiate... · How to combine delegates...
  73. [73]
    Introduction to delegates and events - C# - Microsoft Learn
    Mar 31, 2022 · The first in a series of articles about C# delegates and events. This article introduces basic concepts and discusses language design goals ...
  74. [74]
    Lambda expressions and anonymous functions - C# - Microsoft Learn
    You use a lambda expression to create an anonymous function. Use the lambda declaration operator => to separate the lambda's parameter list from its body.Expression lambdas · Statement lambdas
  75. [75]
    Delegates and lambdas - .NET - Microsoft Learn
    Jan 5, 2022 · Lambda expressions, or just "lambdas" for short, were introduced in C# 3.0 as one of the core building blocks of Language Integrated Query (LINQ) ...
  76. [76]
    Func<T,TResult> Delegate (System) - Microsoft Learn
    The following example demonstrates how to declare and use a Func<T,TResult> delegate. This example declares a Func<T,TResult> variable and assigns it a lambda ...
  77. [77]
    Action<T> Delegate (System) - Microsoft Learn
    You can use the Action<T> delegate to pass a method as a parameter without explicitly declaring a custom delegate.
  78. [78]
    Records - C# reference - Microsoft Learn
    Learn about the record modifier for class and struct types in C#. Records provide standard support for value based equality on instances of record types.
  79. [79]
    The with expression - create new objects that are modified copies of ...
    Learn about a with expression that performs nondestructive mutation of C# records and structures. The `with` keyword provides the means to modify one or ...<|control11|><|separator|>
  80. [80]
    Pattern matching overview - C# - Microsoft Learn
    Pattern matching is a technique where you test an expression to determine if it has certain characteristics.Missing: enhancements | Show results with:enhancements
  81. [81]
    Pattern matching using the is and switch expressions. - C# reference
    Learn about the patterns supported by the `is` and `switch` expressions. Combine multiple patterns using the `and`, `or`, and `not` operators.Microsoft Ignite · If and switch statements · The `is` operatorMissing: design | Show results with:design
  82. [82]
    Expression Trees - C# | Microsoft Learn
    Oct 13, 2025 · You write function arguments, typically using Lambda Expressions, when you create LINQ queries. In a typical LINQ query, those function ...
  83. [83]
    Overview of core .NET libraries - Microsoft Learn
    In addition to the base data types, the System namespace contains over 100 classes, ranging from classes that handle exceptions to classes that deal with core ...
  84. [84]
    System Namespace - Microsoft Learn
    To access types in the System namespace from C# code without having to provide fully qualified type names, include the using System; statement at the ...Classes · Structs
  85. [85]
  86. [86]
  87. [87]
  88. [88]
  89. [89]
    System.IO Namespace
    ### Summary of System.IO Namespace: File, Stream, Path Classes and Operations
  90. [90]
  91. [91]
  92. [92]
  93. [93]
    System.Collections Namespace
    ### Summary of System.Collections: Non-Generic Collections and Legacy Context
  94. [94]
  95. [95]
  96. [96]
  97. [97]
    System.Linq Namespace
    ### Summary of System.Linq: Extension Methods Tied to LINQ
  98. [98]
  99. [99]
  100. [100]
    System.Threading Namespace
    ### Summary of System.Threading: Basic Threading Primitives
  101. [101]
  102. [102]
  103. [103]
  104. [104]
    ECMA-335 - Ecma International
    This Standard defines the Common Language Infrastructure (CLI) in which applications written in multiple high-level languages can be executed in different ...
  105. [105]
    Common Language Runtime (CLR) overview - .NET - Microsoft Learn
    Oct 21, 2025 · The common language runtime makes it easy to design components and applications whose objects interact across languages. Objects written in ...
  106. [106]
    Common Type System - .NET
    ### Summary of Common Type System (CTS)
  107. [107]
    Metadata and Self-Describing Components - .NET | Microsoft Learn
    Apr 20, 2024 · Metadata is binary information describing your program that is stored either in a common language runtime portable executable (PE) file or in memory.
  108. [108]
    Assembly manifest - .NET | Microsoft Learn
    Sep 15, 2021 · An assembly manifest contains all the metadata needed to specify the assembly's version requirements and security identity.
  109. [109]
    Fundamentals of garbage collection - .NET | Microsoft Learn
    The garbage collector (GC) serves as an automatic memory manager. The garbage collector manages the allocation and release of memory for an application.Benefits · Fundamentals of memory
  110. [110]
    Managed Execution Process - .NET - Microsoft Learn
    Apr 20, 2024 · The common language runtime provides the infrastructure that enables execution to take place and services that can be used during execution.
  111. [111]
    <NetFx40_LegacySecurityPolicy> Element - .NET Framework
    May 26, 2022 · In this article​​ Specifies whether the runtime uses legacy code access security (CAS) policy. Code Access Security (CAS) has been deprecated ...Missing: Core | Show results with:Core
  112. [112]
    Most code access security APIs are obsolete - .NET - Microsoft Learn
    Learn about the .NET 5 breaking change in core .NET libraries where most code access security (CAS)-related types in .NET are now obsolete as warning.
  113. [113]
    Language independence and language-independent components
    Dec 20, 2022 · The Common Language Specification is defined in Partition I, Clauses 7 through 11 of the ECMA-335 Standard: Common Language Infrastructure.<|control11|><|separator|>
  114. [114]
    Platform Invoke (P/Invoke) - .NET - Microsoft Learn
    May 10, 2024 · P/Invoke is a technology that allows you to access structs, callbacks, and functions in unmanaged libraries from your managed code.
  115. [115]
    ComImportAttribute Class (System.Runtime.InteropServices)
    ComImportAttribute is a pseudo-custom attribute that indicates that a type has been defined in a previously published type library.Definition · Examples
  116. [116]
    Runtime Callable Wrapper - .NET - Microsoft Learn
    The CLR exposes COM objects through a runtime callable wrapper, which manages calls between a .NET client and a COM object.Missing: ComImport | Show results with:ComImport
  117. [117]
    COM Wrappers - .NET | Microsoft Learn
    Sep 29, 2023 · COM clients and .NET objects interact by using a COM callable wrapper and a runtime callable wrapper. The CLR creates wrappers ...
  118. [118]
    .NET Standard - .NET | Microsoft Learn
    Nov 11, 2024 · Select .NET Standard version ;.NET and .NET Core, 1.0, 1.1, 2.0, 2.1, 2.2, 3.0, 3.1, 5.0, 6.0, 7.0, 8.0, 9.0 ;.NET Framework, 4.5, 4.5.1, 4.5.2, ...
  119. [119]
    ASP.NET Core Blazor JavaScript interoperability (JS interop)
    Nov 19, 2024 · A Blazor app can invoke JavaScript (JS) functions from .NET methods and .NET methods from JS functions. These scenarios are called JavaScript interoperability ...Call JavaScript functions from... · JavaScript location in ASP...
  120. [120]
    About Mono
    These classes are compatible with Microsoft's .NET Framework classes. Mono Class Library - Mono also provides many classes that go above and beyond the Base ...
  121. [121]
    CoreCLR is now Open Source - .NET Blog
    Feb 3, 2015 · We're excited to announce that CoreCLR is now open source on GitHub. CoreCLR is the .NET execution engine in .NET Core, performing functions ...
  122. [122]
    History - Mono Project
    Sep 5: Mono's C# compiler which is written in C# compiles its first program: “Hello world” on Windows using the .NET runtime. The resulting executable runs on ...
  123. [123]
    Another Monkey: Analysis of the Mono Project History and Future ...
    Aug 30, 2024 · Mono provided a C# compiler, a Common Language Runtime (CLR) compatible with Microsoft's implementation, and a set of class libraries that ...<|separator|>
  124. [124]
  125. [125]
    DotGNU Portable.NET
    ### Summary of DotGNU Portable.NET
  126. [126]
    DotGNU Portable.NET - GNU.org
    The DotGNU Portable.NET compiler, cscc, is a modular compiler system with good support for the C# and C programming languages. Work on support for some other ...
  127. [127]
    IL2CPP Overview - Unity - Manual
    The IL2CPP backend converts MSIL (Microsoft Intermediate Language) code (for example, C# code in scripts) into C++ code, then uses the C++ code to create a ...
  128. [128]
    The Rough History of The So Many C# Compilers
    Oct 28, 2017 · And starting from Mono 5.0, Mono started to ship the Roslyn C# compiler. Mono's own C# compilers are no longer (actively) maintained. Note that ...
  129. [129]
    Install Visual Studio and Choose Your Preferred Features
    Sep 9, 2025 · Learn how to install Visual Studio quickly. To reduce the installation footprint, choose your preferred features.Use command-line parameters · Update Visual Studio · Uninstall Visual Studio
  130. [130]
    Visual Studio Professional vs Enterprise - Microsoft Q&A
    Sep 11, 2020 · We would like to know the differences between Visual Studio Professional vs Enterprise. We know that Enterprise has more benefits, but we need more details.
  131. [131]
    Use C# IntelliSense for quick access while coding - Microsoft Learn
    Mar 29, 2024 · C# IntelliSense is a language-specific code-completion aid. It's available to you when you write C# code in the code editor and debug it in the Immediate mode ...
  132. [132]
    Use IntelliSense for quick information & completion - Visual Studio ...
    Jan 27, 2025 · IntelliSense is a code-completion aid that helps you learn about code, track parameters, and add calls with few keystrokes.List Members · Parameter Info · Quick Info
  133. [133]
    Efficient coding, debugging, & keyboard shortcuts - Visual Studio ...
    Jun 2, 2025 · Change auto-insertion of IntelliSense options as you enter code. · Use code snippets. · Paste JSON or XML as classes. · Fix code errors inline.Write Code · Navigate Within Your Code... · Debug Code
  134. [134]
    Installing C# support - Visual Studio Code
    C# language support is provided with the C# Dev Kit extension. You can install it from within VS Code by searching for 'C# Dev Kit' in the Extensions view ( ...
  135. [135]
    C# Dev Kit for Visual Studio Code - Microsoft Learn
    Jul 23, 2025 · The C# Dev Kit is a new Visual Studio Code extension that brings an improved editor-first C# development experience to Linux, macOS, and Windows.
  136. [136]
    Compiler Options - C# reference | Microsoft Learn
    Sep 15, 2021 · This section describes the options interpreted by the C# compiler. Options are grouped into separate articles based on what they control.Missing: Roslyn | Show results with:Roslyn
  137. [137]
    Features - Rider - JetBrains
    Rider is a cross-platform .NET IDE with smart code editing, 2200+ live code inspections, and 1000+ quick-fixes, using the IntelliJ platform and ReSharper  ...Killer code analysis · Navigation and search · Decompiler · Unit testing
  138. [138]
    Get started with unit testing - Visual Studio (Windows) | Microsoft Learn
    Jan 23, 2025 · You can run unit tests in Visual Studio by using third-party test frameworks such as NUnit, Boost, or Google C++ Testing Framework, depending on ...Create Unit Tests · View Live Unit Test Results... · Use A Third-Party Test...
  139. [139]
    Unit testing C# with NUnit and .NET Core - Microsoft Learn
    Oct 28, 2025 · This tutorial takes you through an interactive experience building a sample solution step-by-step to learn unit testing concepts.
  140. [140]
    Install Third-party Unit Test Frameworks - Visual Studio (Windows)
    Apr 17, 2025 · Install third-party unit test frameworks by using NuGet Package Manager. In NuGet Package Manager, search for the test framework you want to install.
  141. [141]
    ECMA-334 - Ecma International
    This specification describes the form and establishes the interpretation of programs written in the C# programming language. It describes.
  142. [142]
    Ecma standards for .NET - Microsoft Learn
    The C# Language and the Common Language Infrastructure (CLI) specifications are standardized through Ecma International®.
  143. [143]
    Anybody May Legally Implement the C# and CLI Specifications - InfoQ
    Jul 7, 2009 · It is important to note that, under the Community Promise, anyone can freely implement these specifications with their technology, code, and ...
  144. [144]
    [PDF] ECMA-334, 7th edition,December 2023
    This specification replaces ECMA-334:2022. Changes from the previous edition include the addition of the following: • Binary integer literals.
  145. [145]
    What's new in C# 13 - Microsoft Learn
    C# 13 includes the following new features. You can try these features using the latest Visual Studio 2022 version or the .NET 9 SDK.Missing: history | Show results with:history
  146. [146]
    Is C# and .NET still relevant in 2026? - Educative.io
    Oct 23, 2025 · C# is simple, powerful, and type-safe. C# is used to build desktop, web, game, and mobile applications. C# supports both static and dynamic ...
  147. [147]
    Overview of .NET Development in 2025 - Baytech Consulting
    Apr 25, 2025 · In 2025, .NET is a unified platform that you can use to build web services, web applications, desktop apps, mobile apps, cloud applications, ...
  148. [148]
    12 Best C# Game Engines For Your Game Development in 2025
    Apr 30, 2025 · Additionally, C#'s widespread use in industry-leading engines like Unity has solidified its position as a go-to language for game developers.
  149. [149]
    The Ultimate Guide to Cross-Platform Game Development in 2025
    Feb 5, 2025 · Xamarin is useable for mobile and desktop game development with C#. ... Flutter comes as a preferred selection for mobile and web-based game ...
  150. [150]
  151. [151]
    Most Popular Technologies 2025 | Stack Overflow Developer Survey
    Most Popular Programming Languages in 2025 ; 8. C#. 27.8% .NET development, gaming ; 9. C++. 23.5%. System programming, gaming.
  152. [152]
    C# Popularity, Usage, and Developer Momentum in 2025 - ZenRows
    May 23, 2025 · On the other hand, the Stack Overflow Developer Survey showed C# being used by 27.1% of all respondents, placing it as the 8th most commonly ...
  153. [153]
    Why C# Developers Are in Hot Demand in Today's Tech Job Market!
    Jul 9, 2025 · One of the biggest reasons behind the rising demand for C# developers in India is the widespread adoption of Microsoft Azure and .NET ...<|separator|>
  154. [154]
    NET Core in 2025: Why I Still Choose It | Let's Code Future | - Medium
    I can write on Windows, deploy to Linux, and even run tests on macOS if needed.
  155. [155]
    .NET Core Cross-Platform Development: Build Apps for Windows, Mac
    Aug 28, 2025 · Cross-platform support started with .NET Core 1.0 in 2016 and continues through .NET 5 and later. The most used versions today are .NET 6 and .
  156. [156]
    Five Game-Changing AI Trends in Q4 2025 Every C# Developer ...
    Oct 30, 2025 · According to recent research, AI agents, ML.NET, Azure AI, and GPT-4 integration are fundamentally transforming C# development in 2025.
  157. [157]
    Build AI and ML applications with .NET and C# | .NET
    Add AI and ML to .NET applications to personalize experiences, gain new insights, automate workflows, and build new types of intelligent applications.
  158. [158]
    Best AI Framework for .NET in 2025: ML.NET, Infer.NET, or Azure AI?
    Mar 27, 2025 · This guide compares Microsoft's three top AI frameworks for .NET developers: ML.NET, Infer.NET, and Azure AI.
  159. [159]
    Why do some developers believe .NET Core has revived the future ...
    Oct 6, 2025 · There are a couple main reasons, chief among them would be: 1. Cross-platform by design. Older .NET framework versions were tightly coupled ...
  160. [160]
    Constraints on type parameters - C# - Microsoft Learn
    The type argument must be or implement the specified interface. Multiple interface constraints can be specified. The constraining interface can also be generic.Generic Classes · Generic Type Parameters - C · Unmanaged types
  161. [161]
    Generic Collections in .NET - Microsoft Learn
    Sep 15, 2021 · List<T> is a generic version of ArrayList. There are generic Queue<T> and Stack<T> classes that correspond to the nongeneric versions. There ...
  162. [162]
    Write LINQ queries - C# - Microsoft Learn
    Jan 18, 2025 · Most queries in the introductory Language Integrated Query (LINQ) documentation are written by using the LINQ declarative query syntax.Example - Query Syntax · Handle Null Values In Query... · Handle Exceptions In Query...
  163. [163]
    Introduction to LINQ Queries - C# | Microsoft Learn
    LINQ offers a consistent model for queries on data across various kinds of data sources and formats. In a LINQ query, you're always working with objects.The Data Source · Classification Of Standard... · Classification Table