DEV Community

Cover image for C# - with expressions
Keyur Ramoliya
Keyur Ramoliya

Posted on

C# - with expressions

In C# with expressions, a feature that simplifies the creation of new objects based on existing instances, is particularly useful for working with immutable data types. This feature is part of the record types enhancement but can also be beneficial in other scenarios where immutability is desired.

Here's how to utilize with expressions in C#:

  1. Create New Objects with Modified Properties:
    with expressions allow you to create a new object by copying an existing object and modifying some of its properties in an immutable way. This is especially useful with record types.

  2. Combine with Record Types for Immutability:
    When used with record types, with expressions provide a seamless way to work with immutable data structures.

Example:

public record Person(string Name, int Age);

public static void Main()
{
    var originalPerson = new Person("Alice", 30);

    // Create a new person based on the original, but with an incremented age
    var aYearOlderPerson = originalPerson with { Age = originalPerson.Age + 1 };

    Console.WriteLine($"Original: {originalPerson}");
    Console.WriteLine($"A Year Older: {aYearOlderPerson}");
}
Enter fullscreen mode Exit fullscreen mode

In this example, the aYearOlderPerson record is created using a with expression based on originalPerson. This new instance has an incremented age, while the rest of the properties are copied from the original. This approach is very useful in scenarios where you have to work with data that should remain immutable after its initial creation, such as in functional programming or when dealing with thread-safe data structures.

with expressions enhance the readability and maintainability of your code when dealing with immutable data, making C# more suitable for functional-style programming patterns.

Top comments (0)