I saw a post in the garden today about the description of nullable types in C #, and it felt good to write a small example.
In C #, the nullable type is described as:nullable<t>, which represents a type that can be empty. It is defined as a struct (struct) and not as a class ... Here's a little demo to see how it's used.
Int? Inttest;
Int? Nullintvalue = new nullable<int> ();
Inttest = 999;
Try
{
1. Output an Interger value
Console.WriteLine ("Output an Interger value: {0}", inttest);
2. Output an boxed (int) value
Object boxedobj = inttest;
Console.WriteLine ("Output an boxed integer type: {0}", Boxedobj.gettype ());
3. Output an unboxed int value
int normalint = (int) boxedobj;
Console.WriteLine ("Output an unboxed integer value: {0}", Normalint);
4. Output an Nullable object
Object nullobj = Nullintvalue;
Console.WriteLine ("Output an nullable equals null?: {0}", (nullobj = = null));
Output an nullable value (Error:non refferenced)
int nullinttest = (int) nullobj;
Console.WriteLine ("Output an nullable value: {0}", nullinttest);
5. Output an value of nullable object
Nullable<int> nullinttest = (nullable<int>) nullobj;
Console.WriteLine ("Unboxed An nullable value: {0}", nullinttest);
int nullinttest = (int) nullobj;
Console.WriteLine ("Unboxed An nullable value: {0}", nullinttest);
}
catch (Exception ex)
{
Console.WriteLine ("Error happend: {0}", ex. Message);
}
Console.readkey ();
The output results are as follows:
In the above code, I tried to unboxing a non-nullable nullable value type instance into a normal value type and a nullable value type (three-in-one), respectively. After that, I boxed a nullable value type instance testnull as a null reference, then successfully unpacking another nullable value type instance (4,5) with no value. if we simply unboxing it to a normal value type at this point, the compiler throws a NullReferenceException exception ...
C # nullable<t> Usage Summary