dcsimg
Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


Tip of the Day
Language: .NET
Expertise: Intermediate
Dec 28, 2006

WEBINAR:

On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning


Use Nullable Types to Assign a Null Value to Value-type Variables

Suppose you want to have a primitive type with a null (or an unknown) value. This is where you would use a nullable type.

Nullable types have the following characteristics:

  • They 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.
  • You can assign a value to a nullable type in the same way you'd assign a value 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;
    
PalaniChamy VijayShankar
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date