What do you think will be output of the following C# code?
using System;
using System.Collections.Generic;
using System.Text;
namespace TestNull
{
class Program
{
static void Main(string[] args)
{
int TestVal;
TestVal = 1;
if (TestVal != null)
{
// Assign null to an integer type
TestVal = null;
Console.WriteLine("TestVal assigned null.");
}
else
{
Console.WriteLine("TestVal cannot be assigned null.");
Console.ReadLine();
}
}
}}
Stop reading further, if you have guessed that executing the code will result in an error.
Error : Cannot convert null to 'int' because it is a value type at the following line:
TestVal = null;
We cannot assign Null to value type variables. This poses a problem when we want to insert a null DateTime or integer value to a DateTime/int field in the database table.
So in order to get out of this error .Net 2.0 provides a option called Nullable Types.If we want to define integer as a Nullable type the following syntax has to be followed
int? <VariableName>=Value.
In our above C# Code
Replace the declaration of
int TestVal to int? TestVal;
If the Variable TestVal has no value it will be assigned null else it will take the Assigned Value.
If you want to check if the value type has any value, use the HasValue property as shown below.
if (TestVal.HasValue)
{
//...do something
}
Nullable type is constructed from the generic Nullable structure. This can be extended to other data types also for example to DateTime , bool etc.
From MSDN.
Nullable types have the following characteristics:
-
Nullable types represent value-type variables that can be assigned the value of null. You cannot create a nullable type based on a reference type. (Reference types already support the null value.)
-
The syntax T? is shorthand for System.Nullable<T>, where T is a value type. The two forms are interchangeable.
-
Assign a value to a nullable type in the same way as for an ordinary value type, for example int? x = 10; or double? d = 4.108;
-
Use the System.Nullable.GetValueOrDefault property to return either the assigned value, or the default value for the underlying type if the value is null, for example int j = x.GetValueOrDefault();
-
Use the HasValue and Value read-only properties to test for null and retrieve the value, for example if(x.HasValue) j = x.Value;
-
The HasValue property returns true if the variable contains a value, or false if it is null.
-
The Value property returns a value if one is assigned, otherwise a System.InvalidOperationException is thrown.
-
The default value for a nullable type variable sets HasValue to false. The Value is undefined.
-
Use the ?? operator to assign a default value that will be applied when a nullable type whose current value is null is assigned to a non-nullable type, for example int? x = null; int y = x ?? -1;
-
Nested nullable types are not allowed. The following line will not compile: Nullable<Nullable<int>> n;