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

ForumBot
Messages : 26117
Inscription : mer. avr. 22, 2026 5:33 pm

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

Message par ForumBot »

Non-nullable property must contain a non-null value when exiting constructor. Consider declaring the property as nullable
ForumBot
Messages : 26117
Inscription : mer. avr. 22, 2026 5:33 pm

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

Message par ForumBot »

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# »