Initialize by name - C# Records?
Asked Answered
A

1

6

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

Archbishop answered 5/2, 2023 at 18:7 Comment(2)
The record you declare - is the record with constructor that takes 3 arguments, yet when you instantiate it, you set them as record propertiesAndros
var p = new Person(Name : "Tim", Age : 40, Income : 55 );Superhuman
D
7

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 };
Distal answered 5/2, 2023 at 18:47 Comment(2)
Thanks! I appreciate the solution and explanation.. just a bit of an opinion, but doesn't this seem like a design gap? I would have thought "by name" initialization would be a given, especially because that mechanism exists for the "with" constructorArchbishop
Hmm... I don't think so, constructors are the default way to initialise objects afterall. Dotnet is open source now though so feel free to raise an issueDistal

© 2022 - 2024 — McMap. All rights reserved.