DEV Community

Cover image for Exploring C# 9.0: New Features That Simplify Your Code
Sebastian Van Rooyen
Sebastian Van Rooyen

Posted on

Exploring C# 9.0: New Features That Simplify Your Code

C# 9.0, released with .NET 5.0, introduces a range of features designed to simplify code, improve readability, and enhance performance. If you've been grappling with verbose code or complex patterns, these updates are here to streamline your development experience. In this article, we'll dive into the new features of C# 9.0, explore their use cases, and show how they can solve common headaches in coding.

1. Record Types

What It Is: Record types are a new reference type in C# that provide built-in support for immutable data. They simplify the creation of data-centric classes and make working with immutable data much easier.

Example:

public record Person(string FirstName, string LastName);
Enter fullscreen mode Exit fullscreen mode

Use Case: Ideal for data transfer objects (DTOs), value objects, or when working with immutable data.

Benefits:

  • Immutability: Records are immutable by default.
  • Value Equality: Records support value-based equality checks.
  • Concise Syntax: Simplifies object creation and deconstruction.

Example Usage:

var person1 = new Person("John", "Doe");
var person2 = new Person("John", "Doe");

// Value equality check
Console.WriteLine(person1 == person2); // True

// Deconstruction
var (firstName, lastName) = person1;
Console.WriteLine($"First Name: {firstName}, Last Name: {lastName}");
Enter fullscreen mode Exit fullscreen mode

Check out how to use records to simplify API data handling:

2. Init-only Properties

What It Is: init accessors allow you to set properties during object initialization but prevent modifications after that.

Example:

public class Book
{
    public string Title { get; init; }
    public string Author { get; init; }
}
Enter fullscreen mode Exit fullscreen mode

Use Case: Ensures properties can only be set at initialization, making objects immutable.

Example Usage:

var book = new Book { Title = "1984", Author = "George Orwell" };
// book.Title = "Animal Farm"; // Error: property is init-only
Enter fullscreen mode Exit fullscreen mode

3. Top-level Statements

What It Is: Allows writing code without requiring a class or namespace, making it easier to create small scripts or console applications.

Example:

using System;

Console.WriteLine("Hello, World!");
Enter fullscreen mode Exit fullscreen mode

Use Case: Simplifies writing simple programs or scripts without boilerplate code.

4. Pattern Matching Enhancements

What It Is: Introduces new patterns such as or patterns, and patterns, and not patterns to simplify complex conditional logic.

Example:

public static void PrintResult(object obj)
{
    if (obj is int or string)
    {
        Console.WriteLine($"Object is an int or string: {obj}");
    }

    if (obj is int and > 10)
    {
        Console.WriteLine($"Integer greater than 10: {obj}");
    }
}
Enter fullscreen mode Exit fullscreen mode

Use Case: Simplifies complex switch statements and if conditions.

5. Records with with Expressions

What It Is: Allows creating a new instance of a record with some properties changed, using the with expression.

Example:

public record Person(string FirstName, string LastName);

var original = new Person("John", "Doe");
var updated = original with { LastName = "Smith" };
Enter fullscreen mode Exit fullscreen mode

Use Case: Useful for creating modified copies of immutable objects.

6. **Primary Constructors (Class-Scoped)

What It Is: Simplifies class construction by allowing parameters to be declared directly in the class declaration.

Example:

public class Person(string firstName, string lastName)
{
    public string FirstName { get; } = firstName;
    public string LastName { get; } = lastName;
}
Enter fullscreen mode Exit fullscreen mode

Use Case: Reduces boilerplate code for classes that only need to pass constructor parameters to properties.

7. Source Generators (Preview)

What It Is: Source Generators enable you to generate code at compile-time, allowing for metaprogramming and code generation within the same compilation context.

Example:

[Generator]
public class MySourceGenerator : ISourceGenerator
{
    public void Initialize(GeneratorInitializationContext context) { }
    public void Execute(GeneratorExecutionContext context)
    {
        // Generate code
    }
}
Enter fullscreen mode Exit fullscreen mode

Use Case: Automates repetitive code tasks, such as generating boilerplate or configuration code.

Conclusion

C# 9.0 introduces several powerful features that can drastically simplify your coding experience. From immutable record types to streamlined constructors and enhanced pattern matching, these updates are designed to make your code more readable, maintainable, and efficient. Whether you're working on data models, writing small scripts, or tackling complex conditional logic, C# 9.0 has you covered.

Stay ahead in your development journey by embracing these features and reducing those coding headaches!

Top comments (0)