Here are examples of C# programming to help you stay up-to-date with the latest language versions. These examples provide a comprehensive overview of C#'s features and capabilities and serve as a valuable resource for anyone looking to learn or improve their skills in this programming language.
Note: Continuous improvements and bug fixes are made within the repository to produce better solutions.
Feature | Description |
---|---|
Params Collections | Demonstrates data passing to functions via the params keyword using IEnumerable , List<T>[] , and ReadOnlySpan<T> . Offers a clean and performance-oriented approach for collection-based data processing scenarios. |
New Escape Sequence | Uses \e , \u001B , and \x1B to emit ANSI escape codes for styled console output (underline, blink, RGB color). Demonstrates safer alternatives to \x1B and dynamic escape code generation. |
Extension Types | Demonstrates extension methods in C# 3.0 and the upcoming C# 13. Highlights the new implicit extension feature, enabling scoped instance and static member extensions. It includes bitwise accessors using modern syntax for ulong . |
The lock statement | Singleton pattern with concurrency control using System.Threading.Lock . Demonstrates task lifecycle management via nested Task instances with AttachedToParent and instance checks using C# 9 is not null pattern matching. |
New LINQ Methods * Index() * CountBy() * AggregateBy() |
Demonstrates advanced LINQ operations using Index , CountBy , and AggregateBy extensions for indexed iteration, grouped counting, and key-based aggregation over collections. Enables more expressive and composable query patterns. |
CreateUnboundedPrioritized | Introduced in .NET 9, Channel.CreateUnboundedPrioritized enables a priority-based, unbounded, thread-safe message queue. This sample demonstrates prioritized, asynchronous message processing—ideal for real-time, concurrent workloads. |
Feature | Description |
---|---|
Keyed Services | The Keyed Service feature in ASP.NET Core allows multiple implementations of the same interface (such as SMS and Email services) to be registered with unique keys and resolved dynamically at runtime based on those keys. |
Primary constructors | A primary constructor defines parameters directly in the class signature, promoting them into the instance scope. This eliminates the need for explicit field declarations and assignments within the constructor, simplifying the code and enabling more direct data access. |
Default values for parameters in lambda expressions | Lambda expressions enable flexible parameter handling using default arguments and the params keyword, eliminating the need for method overloading. Variadic operations can be handled through single-expression definitions. |
Feature | Description |
---|---|
Raw string literals | Demonstrates raw string literals and interpolated raw strings for multi-line text and embedded expressions. Useful for location formatting and structured output in console apps. |
List Patterns Matching | Examples of array pattern matching demonstrating element position, length, wildcard (_ ), slicing (.. ), and comparison (< , >= ) operators. |
Generic Attributes | Type-bound metadata is added using custom and generic Attribute definitions. Designed for reflection-based type resolution scenarios, ensuring compile-time type safety and extensibility. |
File-local types | Demonstrates file-local types scope isolation using file modifier to restrict type visibility to the declaring source file , ensuring encapsulation and minimizing type conflicts across large codebases. |
Static Abstract Members In Interfaces | Demonstrates static abstract interface members for defining compile-time contracts on static properties. Enables polymorphic access to static data without relying on instances. |
User-defined explicit and implicit conversion operators | Demonstrates user-defined implicit/explicit conversions, type-safe casting, and operator overloading using custom Product and Temperature classes for clean, readable transformations. |
Feature | Description |
---|---|
Global using directive | Eliminates the need to declare using statements in each file by enabling common dependencies to be shared project-wide. Provides simple and centralized using management. |
New LINQ Methods * Chunk() * DistinctBy() * Take() |
A minimal demo showcasing how to group, filter, and slice IEnumerable collections using LINQ methods like Chunk , DistinctBy , and range-based Take . |
Feature | Description |
---|---|
Target-typed new expressions | Usage of target-typed new() with constructors, object initializers, collections, records, and tuples. Covers instantiation syntax, member assignment, and common limitations in type inference. |
Pattern matching | Advanced pattern matching with type checks, relational patterns, and logical combinations in control flow and extension methods. |
Record types | Includes modern data modeling approaches with record types such as immutability, value-based equality, deconstruction, and cloning. Object copying with with expression and inheritance support are also illustrated. |
Top-level statements | A minimal C# app built with top-level statements. Showcases argument handling and a static helper method for streamlined execution without explicit entry point declarations. |
Source generator | An example of compile-time code generation using the Source Generator architecture. Implements ISourceGenerator with Execute and Initialize methods based on the Roslyn infrastructure. |
Attributes on local functions | An example code structure that explores how custom attributes applied to local functions and return values can be analyzed at runtime, along with the use of Conditional attributes for conditional compilation. |
Feature | Description |
---|---|
Asynchronous streams | Asynchronous data flow is handled using IAsyncEnumerable for sequential data generation and consumption. With CancellationToken support, external data fetching is managed seamlessly and with controlled interruption. |
Null-Coalescing operator | Safe reference operations, default value assignment, exception throwing, and ToString behavior are illustrated using null-coalescing and null-check operators. Null-safety is tested with nullable reference types and generic methods. |
Default interface methods | Default method bodies in interfaces, overridable behaviors, and multiple implementation scenarios are explored. Additionally, extensibility is examined through virtual methods and constructor variations. |
Static local functions | Static local functions operate with low memory overhead by not capturing surrounding variables. Generic local functions are also supported, enabling calls with type parameters and usage with composite data structures. |
Pattern matching | Control flow and decision logic over polymorphic data types are modeled using various pattern matching techniques (type patterns, property patterns, positional patterns), enabling concise expressions with static type safety. |
Feature | Description |
---|---|
Attributes on local functions | Adds conditional compilation support to local functions via Conditional attributes. Also defines a custom return value attribute and retrieves its metadata at runtime using reflection. |
Local functions | An example that improves encapsulation and readability using local functions. Functions defined within Main remain inaccessible from outside, preserving control and context. Calculations are managed within the local scope. |
Pattern matching | Pattern matching is applied to handle logic specific to different financial instrument types using switch expressions and tuple-based decision structures. Volatility analysis and price check scenarios are modeled with technical examples. |
Tuple types | A comprehensive example on tuple comparison, deconstruction, nesting, and nullable support, along with their use in function parameters and return types. Also includes integration with object initializers. |
Numeric literal syntax improvement | Includes support for digit separators (_ ) and binary literals (0b ) to improve readability in numeric literals. This syntax enhances code maintainability and accuracy by making large numbers easier to parse. |
Immutable collections | An example application showing how IReadOnlyList<T> and IReadOnlyDictionary<TKey, TValue> can be used to define immutable collections and protect them from reinitialization and modification. |
in parameter modifier | A minimal example showing how to use the in parameter modifier for read-only passing of reference types and leveraging immutable structures for performance benefits. |
ArrayPool | Contains three examples that optimize memory management using ArrayPool: returning arrays to the shared pool with and without clearing, and using a custom cached pool. Suitable for high-performance temporary array allocation. |
MemoryPool | Efficiently rents and manages memory using MemoryPool<T> and IMemoryOwner<T> , enabling low-GC, high-performance scenarios with explicit buffer lifecycle control via Dispose . |
Feature | Description |
---|---|
Using static directive | Shows how the using static directive works. Enables direct access to static members from Math , Console , and a custom utility class, improving code readability and simplicity. |
Collection initializers | Highlights the use of collection and index initializers to improve readability and conciseness when initializing Hashtable and Dictionary objects with key-value pairs." |
Feature | Description |
---|---|
Dynamic types | Investigates dynamic types using dynamic , ExpandoObject , and Activator.CreateInstance ; compares runtime and compile-time behaviors. Includes extension methods, overload resolution, and dynamic collections. |
Multicast Delegates | Demonstrates combining multiple methods into a single delegate instance using multicast delegates. Suitable for event handling, callback chaining, and modular invocation patterns. |
DebuggerDisplay | Uses DebuggerDisplay to customize object visualization in the debugger. Displays a formatted summary during debugging instead of relying on ToString() , reducing unnecessary property expansions. |