Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I avoid CS8618 warning occur at the point of declaration?

Tags:

c#

nullable

Assuming the following C# code (and assuming nullable is on):

class Foo
{
    public string Bar;
}

var foo = new Foo { Bar = "some value" };

How can I avoid a CS8618 warning declaring Bar without a default value, but instead only get warning when attempting to construct a Foo without initializing it? I.e., the above to me seems fine, but the following should generate a warning (convertible to an error):

class Foo
{
    public string Bar;
}

var foo = new Foo { };

As Bar is a non-nullable string and therefore a Foo cannot be created without providing a value for it. I ask because the code base I'm converting to have nullable turned on has a lot of this sort of thing. I can work around it by assigning a default dummy value to each such property, but then the compiler won't catch cases where a Foo is getting created without its properties being properly initialized. The only other solution seems to be to write explicit constructors for all such classes, but some of them have 15+ properties, and (IMO) it actually makes the code less readable - esp. because there's no way of enforcing named parameters, so a call like new TextBox { Color = Color.Red, Width = 15, Height = 20, Title = "My Box", FontFace = "Arial" } can become new TextBox(Color.Red, 15, 20, "Arial", "My Box"), which is definitely not preferable for hopefully obvious reasons. It seems like there should be a better way.

like image 537
Dylan Nicholson Avatar asked Nov 14 '25 21:11

Dylan Nicholson


1 Answers

You can use the required modifier in C# 11.

class Foo
{
    public required string Bar; // no nullability warnings
}

var foo = new Foo { Bar = "some value" };

var foo2 = new Foo { }; // won't compile
like image 138
Orion Avatar answered Nov 17 '25 12:11

Orion



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!