What is nullable type in c#?

Nullable types (When to use nullable types) are value types that can take null as value. Its default is null meaning you did not assign value to it. Example of value types are int, float, double, DateTime, etc. These types have these defaults

int x = 0;
DateTime d = DateTime.MinValue;
float y = 0;

For Nullable alternatives, the defualt of any of the above is null

int? x = null; //no value
DateTime? d = null; //no value

This makes them behave like reference types e.g. object, string

string s = null;
object o = null;

They are very useful when dealing with values from database, when values returned from your table is NULL. Imagine an integer value in your database table that could be NULL, such can only be represented with 0 if the c# variable is not nullable – regular integer.

Also, imagine an EndDate column whose value is not determined until an actual time in future. That could be set to NULL in the DB but you’ll need a nullable type to store that in C#

DateTime StartDate = DateTime.Today;
DateTime EndDate? = null; //we don't know yet

Leave a Comment