Sunday, July 9, 2023

C# Nullable String Explained


Look at the following code.
public class Book
{
    public string BookName { get; set; } = "";
}

There is problem with the above code; although it hides the compiler warning. In the above code, if we remove the initialization of BookName, the C# compiler will warn you as shown below. 

A developer can overlook this warning or can remove the warning by initializing the BookName by ZLS i.e. zero length string as done in the above code. But this will give wrong business notion. It will mean that we are initializing the BookName with a name that is not existing in the real world. Who will name the book name as ZLS? Surely, no one. So, assigning ZLS to BookName is bad idea.

Think well. Maybe we have not still decided about the name of the book and will give it name in future. In this case, null value is expected because a null means unknown value. When the book name is not still given, it is unknown. The string? BookName implies that the BookName is not still initialized and will be initialized later somewhere in the code. Right now it is unknown. This is the good idea. To meet this idea, we use nullable string. The code will be as follows.


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

Hot Topics