C# Nullable Types

By default, all the C# Value types are non-nullable, and Reference types called C# nullable types. The default value for Value types is some form of 0. We already discussed the data types categories, i.e., Value types and Reference types in our previous article.

For example, the default value of any C# integer type variable is 0, and they cannot hold null values.

using System;

class Class1
{
  string str = null; // Valid statement
  int i = null;  //Not Valid
}

int i= null is Not valid because the integer is one of the Value types, and all Value types are non-nullable.

Note: Value types can be made nullable using ?

The syntax of the C# Nullable Types

int? i = null; // valid statement

C# introduced this concept of Nullable types to solve the issues in the database while storing some particular data. For instance,

bool AreYouMajor = null; // invalid statement

Bool is a data type that can accept either true or false. But here is a case where null value should be stored in the database if the user did not answer the question 

Are You Major:

In that case, there will be confusion about what data should store in the database. If we store false, i.e., ‘No’, we can not differentiate whether they use answered ‘no’ or didn’t answer. To avoid that confusion, the C# bool variable ‘AreYouMajor’ make as nullable.

i.e., bool? AreYouMajor = null; // valid statement

using System;
class Class
{
  static void Main()
  {
    bool? AreYouMajor = null;
    if (AreYouMajor == true)
    {
      Console.WriteLine("User is major");
    }
    else if (AreYouMajor == false)
    {
      Console.WriteLine("User is not a major");
    }
    else
    {
      Console.WriteLine("User did not answered the question");
    }
  }
 }

OUTPUT

C# Nullable Types