Nullable in C#

 Nullable in C#


Introduction:


Data types in C# are of two types: Value Type and Reference Type; Value types cannot have Null values, but for reference types can have null value.

However, sometime we need to have null values for value types. For example, we may have a class and this class maps to a table in the database. When we map a class to the database, each property of a class will be a column in the table. And a field in the table can be NULL. But if C# does not allow values to be NULL, then we will end up having default values in the fields of the database instead of NULL. 

With nullable, we can store null values. ; Hence, nullables are mainly used to transform c# types of database types.


Syntax:


int? varName = 0;


Methods of Nullable.


When make a variable as Nullable, we can use the following Nullable methods:

  • Value
  • HasValue
  • GetValueOrDefault