Search code examples
c#structurenullable

Nullable<T> Structure


I read Nullable Structure and understand most of it. But I don't know when and why people will use it.


Solution

  • Usage of Nullable<T> is broad. For an example suppose that you have a query that returns the id of last post of specific user on blog:

    int lastId = User.GetLastPostId();
    

    If the user hasn't any post yet, the method returns null and causes an exception. the solution is using Nullable<int> instead of int to avoid error.

    int? lastId = User.GetLastPostId();
    

    In this case you can even check to be null or not:

    if(lastId == null)
        // do something
    else
        // do something
    

    Something like above, suppose you want to use struct instead of class in your code. As far as the struct is ValueType, it can't accept null value and if you want to force the struct to accept null value, you should define it as Nullable.

    Struct Person
    {
        public string Name;
    }
    
    Person p = null; // Error
    Person? p = null; // Correct