C # nullable<t> Usage Summary

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.