I want to be able to write code like this, and then there should be a compiler error if you fail to initialize the property when constructing the object:
public record Person
{
public string Name { get; init; } // this produces a warning, but I don't think it should
public static void Make()
{
new Person { // this should be a compiler error because I didn't initialize Name, but it's not
};
}
}
Obviously the language isn't going to conform to my wishes, it isn't designed the way I wish it were. So I'm wondering if there is an alternative way of writing this to do what I want, without having to implement a constructor. Of course I could define a constructor that has a parameter for each property that needs to be set, but it feels like a lot of extra boilerplate code that features like record
and init
are designed to prevent from being necessary, but actually fail in this endeavor. An acceptable answer doesn't necessarily need to use the record feature, it's just an example of a feature that makes it seem like the designers of C# are trying to help us avoid this kind of extra boilerplate code. I'm looking for something similar to Kotlin's data classes, which record classes are, but they seem to break down for something as simple as requiring the property to bet set to something not null without having to basically write the same code three times for no reason (at the property definition, in the constructor parameters, and in the constructor implementation).
I've been out of the loop with C# for some time, so I guess I'm just wondering if I'm missing something or if defining a custom constructor really is the best you can do.