I activated this feature in a project having data transfer object (DTO) classes, as given below:
public class Connection { public string ServiceUrl { get; set; } public string? UserName { get; set; } public string? Password { get; set; } //... others }
But I get the error:
CS8618
: Non-nullable property 'ServiceUrl' is uninitialized. Consider declaring the property as nullable.
This is a DTO class, so I'm not initializing the properties. This will be the responsibility of the code initializing the class to ensure that the properties are non-null.
For example, the caller can do:
var connection = new Connection { ServiceUrl=some_value, //... }
My question: How to handle such errors in DTO classes when C#8's nullability context is enabled?
Nullable reference types are a compile time feature. That means it's possible for callers to ignore warnings, intentionally use null as an argument to a method expecting a non nullable reference. Library authors should include runtime checks against null argument values.
In C#, the compiler does not allow you to assign a null value to a variable. So, C# 2.0 provides a special feature to assign a null value to a variable that is known as the Nullable type. The Nullable type allows you to assign a null value to a variable.
null isn't a type. From msdn: The null keyword is a literal that represents a null reference, one that does not refer to any object. Nullable types are instances of the Nullable<T> struct which "Represents a value type that can be assigned null."
Nullable variables may either contain a valid value or they may not — in the latter case they are considered to be nil . Non-nullable variables must always contain a value and cannot be nil . In Oxygene (as in C# and Java), the default nullability of a variable is determined by its type.
You can do either of the following:
EF Core suggests initializing to null!
with null-forgiving operator
public string ServiceUrl { get; set; } = null! ; //or public string ServiceUrl { get; set; } = default! ;
Using backing field:
private string _ServiceUrl; public string ServiceUrl { set => _ServiceUrl = value; get => _ServiceUrl ?? throw new InvalidOperationException("Uninitialized property: " + nameof(ServiceUrl)); }
If it's non nullable, then what can the compiler do when the object is initialized?
The default value of the string is null, so you will
either need to assign a string default value in the declaration
public string ServiceUrl { get; set; } = String.Empty;
Or initialize the value in the default constructor so that you will get rid of the warning
Use the !
operator (that you can't use)
Make it nullable as robbpriestley mentioned.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With