Home > OS >  Initialize by name - C# Records?
Initialize by name - C# Records?

Time:02-06

I'm having trouble understanding how to initialize a C# record using named parameters.. This obviously works with more traditional classes with get; set; (or init) properties. Am I missing some special syntax? The reason it matters is that I prefer this kind of initialization to make the code more readable. Thank you

public record Person(string Name, int Age, double Income); 

//this does not work
var p = new Person { Name = "Tim", Age = 40, Income = 55 };

Error Message

CodePudding user response:

What you're doing won't work because under-the-hood, a three-parameter constructor is generated. Record syntax is just syntactic sugar, and it gets lowered into a normal class with some equality contracts.

What you want to do would require a parameterless constructor.

You have two options, use the constructor with named parameters:

var p = new Person( Name: "Tim", Age: 40, Income: 55);

Or flesh out your record a bit to add a parameterless constructor:

public record Person
{
    public Person(string name, int age, double income)
    {
        Name = name;
        Age = age;
        Income = income;
    }
    
    public Person() {}
    
    public string Name { get; init; }
    public int Age { get; init; }
    public double Income { get; init; }
}

You can do this and keep the parameter list using a : this() on the constructor, but I find this is just confusing.

If you declare the record as I have, you can use:

var p = new Person { Name = "Tim", Age = 40, Income = 55 };
  • Related