C# Language Features

Explore the powerful and evolving features of the C# programming language. This section provides in-depth documentation and examples for the latest advancements in C#, helping you write more concise, readable, and efficient code.

Language Integrated Query (LINQ)

LINQ offers a consistent syntax for querying data from various sources, including collections, databases, and XML. It integrates seamlessly into the C# language.


var querySyntax = from n in numbers
                  where n > 5
                  select n;

var methodSyntax = numbers.Where(n => n > 5);
            

Key benefits include:

Learn more about LINQ

Async and Await

The async and await keywords simplify asynchronous programming, allowing you to write non-blocking code that remains readable and manageable.


public async Task<string> FetchDataAsync()
{
    using (HttpClient client = new HttpClient())
    {
        string result = await client.GetStringAsync("http://example.com/data");
        return result;
    }
}
            

This enables:

Deep dive into Async/Await

Pattern Matching

Pattern matching enhances the power of switch statements and conditional expressions, allowing for more sophisticated data decomposition and type checking.


public void ProcessShape(object shape)
{
    switch (shape)
    {
        case Rectangle r when r.Width == r.Height:
            Console.WriteLine($"Square with side {r.Width}");
            break;
        case Circle c:
            Console.WriteLine($"Circle with radius {c.Radius}");
            break;
        case null:
            Console.WriteLine("Shape is null");
            break;
        default:
            Console.WriteLine("Unknown shape");
            break;
    }
}
            

Use pattern matching to:

Explore C# Pattern Matching

Nullable Reference Types

Nullable reference types help you distinguish between references that can be null and those that cannot, reducing the risk of null reference exceptions at runtime.


// Enabled by default in newer C# versions
string? nullableString = null;
string nonNullableString = "Hello";

if (nullableString != null)
{
    Console.WriteLine(nullableString.Length); // Compiler knows this is safe
}
            

Benefits include:

Understanding Nullable Reference Types

Record Types

Record types provide a concise syntax for creating immutable data-holding types with built-in support for value equality.


public record Person(string FirstName, string LastName, int Age);

var p1 = new Person("Jane", "Doe", 30);
var p2 = new Person("Jane", "Doe", 30);

Console.WriteLine(p1 == p2); // True (value equality)
            

Ideal for:

Discover Record Types
Pro Tip: Always refer to the official C# documentation for the most up-to-date information and detailed examples. The language is constantly evolving!

Further Reading