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:
- Simplified data manipulation
- Strong typing and compile-time checking
- Support for various data sources
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:
- Improved responsiveness in UI applications
- Efficient handling of I/O-bound operations
- Scalability for server applications
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:
- Destructure objects based on their properties
- Conditionally match types and values
- Write more declarative code
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:
- Early detection of potential null issues
- Improved code clarity and intent
- Safer API design
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:
- Representing immutable data
- Simplifying data transfer objects (DTOs)
- Reducing boilerplate code