System.Nullable<T> variable
T? variable
T is the underlying type of the variable. It can be a struct but cannot be reference type.
int? i = 10;
double? d1 = 3.14;
bool? flag = null;
char? letter = 'a';
int?[] arr = new int?[10];
Each instance of the above inherits two public read-only properties from Nullable type:
int? x=null;
if(x.HasValue) {...} or
if(x!=null) {…}
bool? x = null;
if(x) // will raise error
This is because in the case of a null value it is not clear what it means in this context – true or false. To avoid this, check HasValue first and then if it is true, cast to bool. Be aware that if cast is made when value is null an InvalidOperationException will be thrown.
int? i = 10;
Console.WriteLine(i.GetType().FullName); //"System.Int32"
is operator operates on Nullable’s underlying types and cannot be used to determine whether a variable is Nullable type.
int? i = 10;
Console.WriteLine(i is int); //"True"
Boxing
bool? b = null;
object bB = b;
if (b == null) { /* True. */ }
if (bB == null) { /* Also true. */ }
Boxed nullable types has full functionality of the underlying type:
double? d = 44.4;
object iBoxed = d;
// Access IConvertible interface implemented by double.
IConvertible ic = (IConvertible)iBoxed;
int i = ic.ToInt32(null);
string str = ic.ToString();
Using Nullable type is very convenient in number of cases and reduce code writing. More info on the topic is available here
Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.
Comments (2)
Commented:
Author
Commented:(un)boxing = conversion.
Here's what Microsoft says about boxing 8-)