jae-l
5/9/2017 - 3:30 AM

Example of using nullable type.

Example of using nullable type.

// Nullable types are reference types.
// There are two ways to define them.

// Difficult syntax.
Nullable<int> i = null;

// Easier syntax.
int? j = i;		// Both declarations of i and j are equivalent.
int? k = 4;

// Print values.
Console.WriteLine("Value i = " + i);
Console.WriteLine("Value j = " + j);
Console.WriteLine("Value k = " + k);

// The .HasValue property indicates if the object has a value or not.
Console.WriteLine("HasValue i = " + i.HasValue);
Console.WriteLine("HasValue j = " + j.HasValue);
Console.WriteLine("HasValue k = " + k.HasValue);	

// The .GetValueOrDefault property returns the value of the object.
// If the object is null, it sets the value to 0.
Console.WriteLine("Default Value i = " + i.GetValueOrDefault());
Console.WriteLine("Default Value j = " + j.GetValueOrDefault());
Console.WriteLine("Default Value k = " + k.GetValueOrDefault());

//  Value i =
//  Value j =
//  Value k = 4
//  HasValue i = False
//  HasValue j = False
//  HasValue k = True
//  Default Value i = 0
//  Default Value j = 0
//  Default Value k = 4