public class Book
{
public string BookName { get; set; } = "";
}
public class Book
{
public string? BookName { get; set; }
}
The reference type string variable BookName is changed into nullable reference type. So, another alternative may be to change such members to nullable reference types.
Another alternative to remove the warning is by using parameterized constructor as given below.
public class Book
{
public Book(string name)
{
BookName = name;
}
public string BookName { get; set; }
}
In this case, default constructor is removed. In case of default constructor, the string type BookName will get its default value which is null. You can use the null forgiving operator or parameterized constructor to indicate that a member is initialized in other code.
The string datatype variable is non-nullable and so it must contain a nun-null value. If still you have doubt, look at the warning.
Read the documentation. CS8618 - Non-nullable variable must contain a non-null value when exiting constructor. Consider declaring it as nullable.
Non-nullable data means that the variables should get a "useful" initialization by the time we use them. Is int type variable initialized with zero a useful initialization in business scenario? Discuss. Other blog on this topics.
No comments:
Post a Comment