0
0
C Sharp (C#)programming~5 mins

With expressions for immutable copies in C Sharp (C#)

Choose your learning style9 modes available
Introduction

With expressions let you create a new object by copying an existing one but changing some parts. This helps keep data safe and unchanged.

When you want to change some details of an object without changing the original.
When working with data that should not be changed after creation, like user info or settings.
When you want to keep old versions of data while making updates.
When you want simple and clear code to copy and update objects.
Syntax
C Sharp (C#)
var newObject = oldObject with { Property1 = newValue1, Property2 = newValue2 };

The original object stays the same; only the new object has changes.

This works with records or types that support 'with' expressions.

Examples
Create a new person with the same name but a different age.
C Sharp (C#)
record Person(string Name, int Age);

var person1 = new Person("Alice", 30);
var person2 = person1 with { Age = 31 };
Copy point p1 but change X coordinate to 7.
C Sharp (C#)
record Point(int X, int Y);

var p1 = new Point(5, 10);
var p2 = p1 with { X = 7 };
Sample Program

This program shows how to copy a book record and change the year without changing the original book.

C Sharp (C#)
using System;

record Book(string Title, string Author, int Year);

class Program
{
    static void Main()
    {
        var originalBook = new Book("C# Basics", "Jane Doe", 2020);
        var updatedBook = originalBook with { Year = 2023 };

        Console.WriteLine($"Original: {originalBook.Title}, {originalBook.Author}, {originalBook.Year}");
        Console.WriteLine($"Updated: {updatedBook.Title}, {updatedBook.Author}, {updatedBook.Year}");
    }
}
OutputSuccess
Important Notes

With expressions only work with records or types that support them.

They help keep your data safe by avoiding accidental changes.

Summary

With expressions create new objects by copying and changing some parts.

They keep the original object unchanged.

Useful for working with data that should not be changed directly.