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

WPF Overview-Part-II

This post is in continuation to the last post. In this Post I’ll be exploring the Dependency Properties Dependency properties are similar to CLR properties with more advanced and complex features. The main difference between the CLR properties and dependency properties is, that the value of a normal .NET property is read directly from a private member in your class, whereas the value of a DependencyProperty is resolved dynamically when calling the GetValue() method that is inherited from DependencyObject . In case this description did not make sense, no need to worry, It will become clear by the time you reach end of this article. How the Value is Resolved in Dependency properties Every time a dependency property is accessed, it internally resolves the value by following the precedence from high to low. It checks if a local value is available, if not, check if a custom style trigger is active and I the similar manner continues until it finds a value. At last the default value is alwa...

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

Authentication using Social Networking portals(Facebook, Gmail, and Yahoo)

There are tons of sites, which offer sign on using the social networking site credentials (Facebook, gtalk, twitter and the list continues).It can be termed a “SINGLE SIGNON” and offers a lot of benefits compared to traditional database authentication approach. However, not storing user credentials in the DB imposes an additional risk. How to track who all logged into the system. Now the question is, which approach to follow. The best approach is to use inbuilt asp.net users for storing the logging info about user activities and using single signon technique for authentication. This article will explore the approach and provide the details of implementation using some third party libraries and customizing it to the requirements. The Authentication will be done using the following networking portals Yahoo  Gmail Facebook    Special thanks to my friend Sumit Khandelwal, for implementation of Facebook part (in fact he did it all!!) Except Facebook, all other ca...