Introduction
Familiar with '?' and '??' ?
Seeing that some C# developers are not acquainted with
nullable types. That is perhaps because they can be avoided - meaning you can "get along" without them.
However, being that the nullable types make the code more friendly and simpler to read. And, in some cases the functionality can be easier implemented.
I think it's worth a
tip post.
Using Nullable Types in the code
Basically, these are primitives that can have a null value, they can represent the range of values you are familiar with and an additional null value. Nullable types are instances
of the System.Nullable<T>
struct.
Note: 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, this is of course because Reference types already support the null value
and they will work with the following code, using the ? char to identify the nullable attribute
double? d = null;
double d2 = d ?? 3.141592653589793;
You can use the property HasValue
to check if it is not null:
int? num = null;
if (num.HasValue == true)
{
System.Console.WriteLine("num = " + num.Value);
}
else
{
System.Console.WriteLine("num = Null");
}
Check out MSDN's Nullable Types article (VS2012 version): http://msdn.microsoft.com/en-us/library/1t3y8s4s(v=vs.110).aspx
Points of Interest
Note: The following code
...
DateTime? dt = new DateTime();
dt = null;
return dt.ToString();
will return String.Empty
.
Note: Nested nullable types are not allowed. The following line will not compile:
Nullable<Nullable<int>> n;
Note: Use the Nullable<T>.GetValueOrDefault
method 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();
GetType
Calling GetType
on a Nullable type causes a boxing operation to be performed when the type is implicitly converted to Object
. Therefore GetType
always returns a Type
object that represents the underlying type, not the Nullable type.
int? i = 5;
Type t = i.GetType();
Console.WriteLine(t.FullName);
Boxing a Nullable Type
Nullable objects and their boxed counterpart can be tested for null:
bool? b = null;
object boxedB = b;
if (b == null)
{
}
if (boxedB == null)
{
}
Boxed nullable types fully support the functionality of the underlying type:
double? d = 44.4;
object iBoxed = d;
IConvertible ic = (IConvertible)iBoxed;
int i = ic.ToInt32(null);
string str = ic.ToString();
Summary
So, lets make the world a better place by using nullable types...
History
v1.0.0.0.