Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# record - using with keyword to modify properties

I recently ran into the record keyword in C#, I'm able to create a an instance of a record and modify it both by assigning a value regularly and both by using the keyword with.

Is there any difference between the two ways, when should one use with?

public record Car{

    public Car(string name, int age){
        Name = name;
        Age = age;
    }

    public string Name;
    public int Age;
}


public static void Main()
{
    var car = new Car("Reno", 15);
    car.Name = "Honda";
    
    Console.WriteLine(car.Name);
    
    car = car with {Name = "BMW"};
    
    Console.WriteLine(car.Name);
}
like image 799
Ran Turner Avatar asked Dec 27 '25 14:12

Ran Turner


1 Answers

One of the main reasons for records introduction in C# - make it easier to create immutable data models. with functionality was created to provide an easy to use syntax to create a copy of immutable instance with changed properties. So car = car with {Name = "BMW"}; actually does not modify the original instance (note that record's are reference types, unless they are declared as record struct's) but creates a new one and assigns it to the variable. The difference can easily be seen with the following code:

var car = new Car("Reno", 15);
var car2 = car;
car.Name = "Honda";
    
Console.WriteLine(car.Name);  // "Honda"
Console.WriteLine(car2.Name); // "Honda"
    
car2 = car with {Name = "BMW"};
    
Console.WriteLine(car2.Name); // "BMW" 
Console.WriteLine(car.Name);  // "Honda"

Also couple of notes:

  • it is recommended to use autoproperties instead of fields, i.e.:
public record Car
{
    public Car(string name, int age)
    {
        Name = name;
        Age = age;
    }

    public string Name { get; set; };
    public int Age { get; set; };
}
  • in case you need immutable data records provide neat syntax which automatically generates constructor and init-only properties:
public record Car(string Name, int Age);
like image 191
Guru Stron Avatar answered Dec 30 '25 04:12

Guru Stron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!