Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to tell compiler that property MUST be initialized

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:

enter image description here

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.

like image 803
Kjara Avatar asked Oct 28 '25 05:10

Kjara


1 Answers

In C# 11 you can use the required keyword in combination with init-only properties, as described here, (see also What's new in C# 11 ).

For your specific example this would become

public class Foo
{
    public required string Bar { get; init; }
    public required IImmutableSet<int> Baz { get; init; }
}

This syntax is also previously suggested by @Dai in a comment to the original question. But this really deserves a proper answer!

like image 124
kolis Avatar answered Oct 29 '25 20:10

kolis



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!