Thursday, October 21, 2010

Nullable Basics, Boxing, Nullable Operator

using System;

class NullableBasics
{
static void DisplayValue(int? num)
{
if (num.HasValue == true)
{
Console.WriteLine("num = " + num);
}
else
{
Console.WriteLine("num = null");
}

// num.Value throws an InvalidOperationException if num.HasValue is false
try
{
Console.WriteLine("value = {0}", num.Value);
}
catch (InvalidOperationException e)
{
Console.WriteLine(e.Message);
}
}

static void Main()
{
DisplayValue(1);
DisplayValue(null);
}
}





using System;

class NullableBoxing
{
static void Main()
{
int? a;
object oa;

// Assigns a to Nullable (value = default(int), hasValue = false).
a = null;

// Assigns oa to null (because x==null), not boxed "int?".
oa = a;

Console.WriteLine("Testing 'a' and 'boxed a' for null...");
// Nullable variables can be compared to null.
if (a == null)
{
Console.WriteLine(" a == null");
}

// Boxed nullable variables can be compared to null
// because boxing a nullable where HasValue==false
// sets the reference to null.
if (oa == null)
{
Console.WriteLine(" oa == null");
}

Console.WriteLine("Unboxing a nullable type...");
int? b = 10;
object ob = b;

// Boxed nullable types can be unboxed
int? unBoxedB = (int?)ob;
Console.WriteLine(" b={0}, unBoxedB={0}", b, unBoxedB);

// Unboxing a nullable type set to null works if
// unboxed into a nullable type.
int? unBoxedA = (int?)oa;
if (oa == null && unBoxedA == null)
{
Console.WriteLine(" a and unBoxedA are null");
}

Console.WriteLine("Attempting to unbox into non-nullable type...");
// Unboxing a nullable type set to null throws an
// exception if unboxed into a non-nullable type.
try
{
int unBoxedA2 = (int)oa;
}
catch (Exception e)
{
Console.WriteLine(" {0}", e.Message);
}
}

}





using System;

class NullableOperator
{
static int? GetNullableInt()
{
return null;
}

static string GetStringValue()
{
return null;
}

static void Main()
{
// ?? operator example.
int? x = null;

// y = x, unless x is null, in which case y = -1.
int y = x ?? -1;
Console.WriteLine("y == " + y);

// Assign i to return value of method, unless
// return value is null, in which case assign
// default value of int to i.
int i = GetNullableInt() ?? default(int);
Console.WriteLine("i == " + i);

// ?? also works with reference types.
string s = GetStringValue();
// Display contents of s, unless s is null,
// in which case display "Unspecified".
Console.WriteLine("s = {0}", s ?? "null");


Console.ReadLine();
}
}

No comments: