Framework Fundamentals Tips: Nullable Value Types

I am writing some of the .net fundamental tips that will rarely come to me apparent when I do coding. I guess that is true for some of you. One of them is Nullable Value Types. An extraordinary feature and a privilege reserved only for Reference object in previous versions of .NET (1.1). The Nullable type is a featured introduced since .NET 2.0. This allows a value type variable to hold null value and does not force the developer to initialize the variable to avoid possible confusion. This feature also allows you to check whether a variable has assigned a value or not.
Syntax for declaring a variable as Nullable (C#)


Nullable b = null;

OR

boll? b = null


Declaring a variable as Nullable enables two key members which are “HasValue” and “Value”. HasValue allows you to check whether a value has been set or not and Value member is used to access the value. Here is simple example that will test whether a Nullable bool variable is set or not

Example 1: to demonstrate Nullable value type
private void button1_Click(object sender, EventArgs e)
{
bool? b = null;
b = true; // comment this line for null test
if (b.HasValue)
{
MessageBox.Show("The value of B is : " + b.Value);
}
else
{
MessageBox.Show("The value of B is not set : ");
}
}

No comments: