I have a class like e.g. this:
public class Foo
{
public string Bar { get; init; }
public IImmutableSet<int> Baz { get; init; }
}
When I write it that way, I get a compiler warning
Non-nullable property 'Bar' must contain a non-null value when exiting constructor. Consider declaring the property as nullable. csharp(CS8618)
There is much content addressing this (e.g. here), but as far as I can see, it is just about how to get rid of the message by either setting a default value or by switching off compiler warnings using a "fake-default" like null!
.
But in my case, a default value does not make sense. Instead, I'd like to tell the compiler that these properties must be set explicitly, so that it complains if any of them was NOT set prior to using the object. Just like this is the case with unassigned local variables:
Is that possible, and if yes, how?
I know I could just define a single constructor with arguments, so that using that constructor is the only way to create a new instance. But since I have lots of classes like the above, I would need to write quite of lot of extra code (i.e. the constructors). It'd also be clearer for readers of my code if there was a kind of "must-be-initialized" flag.