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...

WCF-REST Services-Part-II

HOW REST is implemented in WCF Part-I of the series explored the REST conceptually and this post will explore how REST is implemented in WCF. For REST implementation in WCF, 2 new attributes namely WebGetAttribute and WebInvokeAttribute are introduced in WCF along with a URI template mechanism that enables you to declare the URI and verb to which each method is going to respond. The infrastructure comes in the form of a binding ( WebHttpBinding ) and a behavior ( WebHttpBehavior ) that provide the correct networking stack for using REST. Also, there is some hosting infrastructure help from a custom Service¬Host ( WebServiceHost ) and a ServiceHostFactory ( WebServiceHostFactory ). How WCF Routes messages WCF routes network messages to methods on instances of the classes defined as implementations of the service. Default behavior ( Dispatching ) for WCF is to do this routing based on the concept of action. For this dispatching to work, an action needs to be present in ev...

WebMatrix-The Swiss Army knife from Microsoft

  What’s more in store for Web developers, ASP.Net 4.5(with full support for HTML 5 , CSS 3 amd Javascript) and to complement it, is the new awesome tool-WebMatrix. WebMatrix combines five products in one, letting you install, develop, optimize, deploy and manage your sites and databases. With support for the latest web standards like HTML5 & CSS3, multiple frameworks like ASP.NET & PHP, and multiple database engines like MySQL & SQL Server ..and what’s even better…it FREE!! ! ( Download Webmatrix ). To learn more about webmatrix, I recomment the following video. WebMatrix-An intro The tools promises a lot and I have already downloaded a copy and started playing with it. Hope the information  here is useful. Till next we connect…. Happy Learning.