Non-nullable property must contain a non-null value when exiting constructor. Consider declaring the property as nullable

Clippy
Messages : 22157
Inscription : mer. 22 avr. 2026, 17:33

Non-nullable property must contain a non-null value when exiting constructor. Consider declaring the property as nullable

Message par Clippy »

Non-nullable property must contain a non-null value when exiting constructor. Consider declaring the property as nullable
Clippy
Messages : 22157
Inscription : mer. 22 avr. 2026, 17:33

Re: Non-nullable property must contain a non-null value when exiting constructor. Consider declaring the property as nullable

Message par Clippy »

The compiler is warning you that the default assignment of your string property (which is null) doesn't match its stated type (which is non-null `string`).

This is emitted when [nullable reference types](https://learn.microsoft.com/en-us/dotnet/csharp/nullable-references) are switched on, which changes all reference types to be non-null, unless stated otherwise with a `?`.

For example, your code could be changed to

```
public class Greeting
{
public string? From { get; set; }
public string? To { get; set; }
public string? Message { get; set; }
}

```

to declare the properties as nullable strings, or you could give the properties defaults in-line or in the constructor:

```
public class Greeting
{
public string From { get; set; } = string.Empty;
public string To { get; set; } = string.Empty;
public string Message { get; set; } = string.Empty;
}

```

if you wish to retain the properties' types as non-null.
Répondre

Revenir à « .NET & C# »