A variable of a nullable type can be used to store the normal range of values allowed by the underlying data type plus the Null. Nullable types are instances of System.Nullable.
Since reference types already supports Null, nullable types represent value type variables which supports null.
For example Nullable<bool> (or spoken like nullable of bool) can be used to store true, false and null.
There are two ways to declare a nullable variable.
Method 1
int? i; // Declaring
i = null; // Initializing
int? i = 4; // Declariong and initializing
Method 2
Nullable<int> a; // Declaring
a = 4; // Initializing
Nullable<int> a = null; // Declariong and initializing
As you see above assigning values to a nullable is same as for a normal variable. But when retrieving the value you need to be little careful.
Method 1 – Using GetValueOrDefault
GetValueOrDefault property is available for nullable variables. If the variable is null it will get the default value for the type otherwise the actual value it contains.
textBox1.Text += "Value of i - " + i.GetValueOrDefault();
Method 2 – Using variable.Value
When you are going to retrieve the value inside the variable using .Value be careful to first check whether there is actually a value in the variable, otherwise .Net will generate an InvalidOperationException with a description of “Nullable object must have a value”.
// \r\n is used to insert a new line.
if (i == null)
textBox1.Text += "\r\n" + "i is Null";
else
textBox1.Text += "\r\n" + "i is - " + i.Value;
or
// Environment.NewLine is equal to placing a new line or \r\n.
if (a.HasValue)
textBox1.Text += Environment.NewLine + "a has - " + a.Value;
else
textBox1.Text += Environment.NewLine + "a has Null";
The full code would look like the following.
- // Declaring Method 1
- int? i; // Declaring
- i = null; // Initializing
- //int? i = 4; // Declariong and initializing
- // Get value using GetValueOrDefault().
- textBox1.Text += "Value of i - " + i.GetValueOrDefault();
- // \r\n is used to insert a new line.
- if (i == null)
- textBox1.Text += "\r\n" + "i is Null";
- else
- textBox1.Text += "\r\n" + "i is - " + i.Value;
- // Declaring Method 2
- //Nullable<int> a; // Declaring
- //a = 4; // Initializing
- Nullable<int> a = 4; // Declariong and initializing
- // Environment.NewLine is equal to placing a new line or \r\n.
- if (a.HasValue)
- textBox1.Text += Environment.NewLine + "a has - " + a.Value;
- else
- textBox1.Text += Environment.NewLine + "a has Null";
The output would be,
Value of i - 0
i is Null
a has – 4
You could use the ?? operator to assign the default value for a non nullable variable while the nullable contains null as the current value.
int? Null_X = null;
int NonNull_y = Null_X ?? -1;
No comments:
Post a Comment