[C#] Nullable Types

A primitive type in C# is a value type. Therefore it should have a value and cannot be null. But in DB applications, null values are particularly important. Therefore C# 2.0 included nullable types (thanks to the support of generics).

 

1. Nullable Types – System.Nullable<T>

Suppose you have an integer variable. You can assign any integer value to it but not an empty value. To integrate with the database, a special value (such as -1) is treated as null. But this approach is not optimal.

Nullable types are specifically designed to support null values. The “System.Nullable<T>” is the main construct for nullable types.

  • public struct Nullable<T> where T : struct, new()

It has the following properties:

  • public bool HasValue { get; }
  • public T Value { get; }
Nullable<int> dbIntVal = new Nullable<int>();

if (dbIntVal.HasValue)
  Console.WriteLine("Value = {0}", dbIntVal.Value);
else
  Console.WriteLine("Value is null");

 

2. Shortcut Syntax – ‘?’ notation

C# provides a very nice way to use null types. Rather than defining Nullable<T> types, you can define null variables just by suffixing the question mark ‘?‘.

int? dbIntVal = null;

if (dbIntVal.HasValue)
  Console.WriteLine("Value = {0}", dbIntVal.Value);
else
  Console.WriteLine("Value is null");

 

3. Checking Null – ‘??’ operator

You can use the “HasValue” property to check whether the value is null. And then you can access the value using the “Value” property. The following code can be used in many places.

int? dbIntVal = null;
int intVal =  dbIntVal.HasValue ? dbIntVal.Value : -1;

C# provides the ‘??‘ operator as a shortcut to the code above.

int? dbIntVal = null;
int intVal =  dbIntVal ?? -1;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s