C# Nullable Types

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

For example, the default value of any C# integer type variable is 0, and they cannot hold nullable 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

This C# language introduced the 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 a 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 nullable type.

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
Categories C#