Skip to main content

C# Nullable Types


Nullable Types:

Nullable Types is a new concept (introduced in .Net 2.0), using which, a null value can be assigned to Value Types.


Nullable types concept is not vital for Reference Types as these can be initialized to null;

Nullable types are instances of the System.Nullable struct.
A nullable type can represent the normal range of values for its underlying value type, and an additional null value.

 For example, If an integer is used along with nullable type, it can be assigned any value (defined in its range) and in addition it can be assigned a null value as well.

 

Nullable Types Basics:

 Nullable types have the following characteristics:

Syntax:

T?  value type

(It is shorthand for System.Nullable, where T is a value type. The two forms can be used in-interchange.)
T can be any value type including struct;but, cannot be a reference type.


Nullable Types Members:

Each instance of a nullable type has two public read-only properties: 

  • HasValue

HasValue is of type bool.  If the variable contains a non-null value,It is set to true  

  • Value

Value is of the same type as the underlying type.
If HasValue is true, Value contains a meaningful value.
 If HasValue is false, and Value is accessed, InvalidOperationException is thrown.

The default value for a nullable type variable sets HasValue to false. The Value is undefined

System.Nullable.GetValueOrDefault   property is used 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 ();
.
Nested nullable types are not allowed. The following line will not compile: 
Nullable> n;

Nullable Types Conversion:

Explicit Conversions

A nullable type can be cast to a regular type, either explicitly with a cast, or by using the Value property. For example:
 

int? pp = null;

      int nontcompile = pp   
      (Will not compile, null cannot be assigned  to value type without using nullable types).

int compilewitherror = (int) pp;     
(Compiles, throw exception if pp is null. Nullable object must have a value error is encountered at runtime)



int compilewitherror1= pp.Value; 
(Compiles, throw exception if pp is null. Nullable object must have a value error is encountered at runtime)


Implicit Conversions

A variable of nullable type can be set to null with the null keyword, as shown below:
int? p1 = null;

The conversion from an ordinary type to a nullable type, is implicit.
int? x2;
x2 = 10;  // Implicit conversion.

Operators

Any operator that exist for value types can used by nullable types.
These operators produce a null value if the operands are null;
If the values are not null, normal operation, as in case of value types is performed.

Let’s consider an example
Here we define two nullable types integer variable
int? a = 10;
int? b = null;

Now if a++ or a -- operation is performed, it will increment/decrement the value by 1.

Consider the addition a+b, here the result will be null, as b is null

A comparison of two nullable types which are both null will be evaluated to true, However if one of the nullable types is null, the comparison is always evaluated to be false.


?? Operator

The ?? operator returns the left-hand operand if it is not null, or else it returns the right operand.

A nullable type can contain a value, or it can be undefined.
The ?? operator defines the default value to be returned when a nullable type is assigned to a non-nullable type.
 If a nullable type is assigned to a non-nullable type without using the ?? operator, compile-time error is generated. If a cast is used and the nullable type is currently undefined, an InvalidOperationException exception will be thrown.

Example:
protected void Page_Load(object sender, EventArgs e)
    {
        int? nullinterger = null;
        int y = nullinterger ?? -1;

         int nullordefault = GetNullableInt() ?? default(int);

        string nullstring = GetStringValue();
        Response.Write(nullstring ?? "Unspecified");

    }
        static int? GetNullableInt()
    {
        return null;
    }

    static string GetStringValue()
    {
        return null;
    }

Code described above shows how ?? operator can be used.The vital point to understand here is, if left is null, right is the value and vice-versa.

The Following Code provides the implementation of the topics discussed here.

  protected void Page_Load(object sender, EventArgs e)
    {
        //?? Operator Test
        int? nullinterger = null;
        int y = nullinterger ?? -1;

         int nullordefault = GetNullableInt() ?? default(int);

        string nullstring = GetStringValue();
        Response.Write("?? Operator Result:"+" ");
        Response.Write(nullstring ?? "Unspecified");
        Response.Write("");

        //Explicit Conversion TEst
        //int k = nullinterger.Value;
        //Will Thow exception, comment it to run the Code
       // Response.Write(nullinterger.Value.ToString());
       
        // implicit ConversionTest
        int? p1 = null;
        int? x2;
         x2 = 10;
         Response.Write("Implicit ConversionTest Result:"+" "+x2.ToString()+"");



       //Operator Test
        int? nonnull = 20;
        nonnull = nonnull + nullinterger;
        Response.Write("Operator Test Result:" + " " + nonnull.ToString() + "");
       


    }

    //Helper Methods
        static int? GetNullableInt()
    {
        return null;
    }

    static string GetStringValue()
    {
        return null;
    }
       
}


Gist: The Nullable Types add great functionality enhacements to the value types and can prove invaluable in database interaction code, where null value are used frequently.


Hope this article was Helpful.

Please don’t hesitate to comment on the article, does not matter  even if it is a criticism as I believe in Continuous learning and your comments might add to it.

Till the time we connect Next, Happy Coding!!!

Comments

Popular posts from this blog

Asp.Net 4.0: An Overview-Part-III

This is the last post in the series which will explore the following new features of ASP.Net 4.0  Performance Monitoring for Individual Applications in a Single Worker Process Web.config File Refactoring Permanently Redirecting a Page Expanding the Range of Allowable URLs Performance Monitoring for Individual Applications in a Single Worker Process It is a common practice to host multiple ASP.NET applications in a single worker process, In order to increase the number of Web sites that can be hosted on a single server. This practice results in difficulties for server administrators to identify an individual application that is experiencing problems. ASP.NET 4 introduces new resource-monitoring functionality introduced by the CLR. To enable this functionality, following XML configuration snippet is added to the aspnet.config configuration file.(This file is located in the directory where the .NET Framework is installed ) <?xml version="1.0" encoding="UTF-8...

Covariance and Contravariance-General Discussion

If you have just started the exploration of .Net Framework 4.0, two terms namely Covariance and Contravariance might have been heard. The concept that these terms encapsulate are used by most developer almost daily, however there has never been any botheration about the terminologies. Now, what actually these terms mean and how are these going to affect us as a developer, if we dive in to the details. The simple answer is it’s always good to know your tools before actually using them. Enough philosophy, let’s get to the business. Starting the discussion let me reiterate that in addition to Covariance and Contravariance, there is another terminology, Invariance. I’ll by start here by diving into the details of Invariance and then proceed further. Invariance: Invariance can be better understood by considering the types in .Net.>net has basically two type, value-types and reference-types. Value types (int, double etc) are invariant i.e. the types can’t be interchanged either ...

Advanced WCF

In this post, I am sharing the link of articles about  advanced topics in WCF. The List of articles is exhaustive and can serve as your repository for all WCF queries. Concurrency,Throttling & Callbacks  WCF Concurrency (Single, Multiple and Re entrant) and Throttling   WCF-Interop and BinarySecurityToken  WCF Callbacks  Creating Web Services From WSDL Link1 Link2 Link3 Link4 WCF-Security WCF over HTTPS   Transport Security(basic)/HTTPS UserNamePasswordValidator ServerCertificateValidationCallback 9 simple steps to enable X.509 certificates on WCF - CodeProject http://www.codeproject.com/KB/WCF/9StepsWCF.aspx?display=Print Message Security(Certificate)/PeerTrust Securing WCF Services with Certificates. - CodeProject http://www.codeproject.com/KB/WCF/wcf_certificates.aspx Message Security(Certificate)/ChainTrust How To Configure WCF Security Using Only X.509 Certificates - CodePr...