Friday 11 April 2014

Nullable Type in C#

Nullable type is new concept introduced in C#2.0 which allow user to assingn null value to primitive data types of C# language. Important to not here is Nullable type is Structure type.
Nullable types (When to use nullable types) are value types that can take null as value. Its default is null meaning you did not assign value to it. Example of value types are int, float, double, DateTime, etc. These types have these defaults
int x = 0;
DateTime d = DateTime.MinValue;
float y = 0;
For Nullable alternatives, the defualt of any of the above is null
int? x = null; //no value
DateTime? d = null; //no value
This makes them behave like reference types e.g. object, string
string s = null;
object o = null;
They are very useful when dealing with values from database, when values returned from your table is NULL. Imagine an integer value in your database table that could be NULL, such can only be represented with 0 if the c# variable is not nullable - regular integer.
Also, imagine an EndDate column whose value is not determined until an actual time in future. That could be set to NULL in the DB but you'll need a nullable type to store that in C#
DateTime StartDate = DateTime.Today;
DateTime EndDate? = null; //we don't know yet
Nullable types are instances of the System.Nullable<T> struct. A nullable type can represent the correct range of values for its underlying value type, plus an additional nullvalue. For example, a Nullable<Int32>, pronounced "Nullable of Int32," can be assigned any value from -2147483648 to 2147483647, or it can be assigned the null value. ANullable<bool> can be assigned the values true false, or null. The ability to assign null to numeric and Boolean types is especially useful when you are dealing with databases and other data types that contain elements that may not be assigned a value. For example, a Boolean field in a database can store the values true or false, or it may be undefined.
class NullableExample
{
    static void Main()
    {
        int? num = null;

        // Is the HasValue property true? 
        if (num.HasValue)
        {
            System.Console.WriteLine("num = " + num.Value);
        }
        else
        {
            System.Console.WriteLine("num = Null");
        }

        // y is set to zero 
        int y = num.GetValueOrDefault();

        // num.Value throws an InvalidOperationException if num.HasValue is false 
        try
        {
            y = num.Value;
        }
        catch (System.InvalidOperationException e)
        {
            System.Console.WriteLine(e.Message);
        }
    }
}
The example will display the output:
num = Null
Nullable object must have a value.
  • Nullable<t> type is also a value type.

  • Nullable Type is of struct type that holds a value type (struct) and a Boolean flag, named HasValue, to indicate whether the value is null or not.
  • Since Nullable<t> itself is a value type, it is fairly lightweight. The size of Nullable<T> type instance is the same as the size of containing value type plus the size of a boolean.
  • The nullable types parameter T is struct. i.e., you can use nullable type only with value types. This is quite ok because reference types can already be null. You can also use the Nullable<T> type for your user defined struct.
  • Nullable type is not an extension in all the value types. It is a struct which contains a generic value type and a boolean flag.


Nullable Types Overview

Nullable types have the following characteristics:
  • Nullable types 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 Nullable<T>, where T is a value type. The two forms are interchangeable.
  • Assign a value to a nullable type just as you would for an ordinary value type, for example int? x = 10; or double? d = 4.108. A nullable type can also be assigned the value null: int? x = null.
  • Use the Nullable<T>.GetValueOrDefault method 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, as shown in the following 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 HasValue is false. The Value property has no default value.
    • You can also use the == and != operators with a nullable type, as shown in the following example: if (x != null) y = x;
  • 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 exampleint? x = null; int y = x ?? -1;
  • Nested nullable types are not allowed. The following line will not compile: Nullable<Nullable<int>> n;
C# provides a special data types, the nullable types, to which you can assign normal range of values as well as null values.
For example, you can store any value from -2,147,483,648 to 2,147,483,647 or null in a Nullable< Int32 > variable. Similarly, you can assign true, false or null in a Nullable< bool > variable. Syntax for declaring a nullable type is as follows:
< data_type> ? <variable_name> = null;
The following example demonstrates use of nullable data types:
using System;
namespace CalculatorApplication
{
   class NullablesAtShow
   {
      static void Main(string[] args)
      {
         int? num1 = null;
         int? num2 = 45;
         double? num3 = new double?();
         double? num4 = 3.14157;
         
         bool? boolval = new bool?();

         // display the values
         
         Console.WriteLine("Nullables at Show: {0}, {1}, {2}, {3}", 
                            num1, num2, num3, num4);
         Console.WriteLine("A Nullable boolean value: {0}", boolval);
         Console.ReadLine();

      }
   }
}
When the above code is compiled and executed, it produces the following result:
Nullables at Show: , 45,  , 3.14157
A Nullable boolean value:

The Null Coalescing Operator (??)

The null coalescing operator is used with the nullable value types and reference types. It is used for converting an operand to the type of another nullable (or not) value type operand, where an implicit conversion is possible.
If the value of the first operand is null, then the operator returns the value of the second operand, otherwise it returns the value of the first operand. The following example explains this:
using System;
namespace CalculatorApplication
{
   class NullablesAtShow
   {
         
      static void Main(string[] args)
      {
         
         double? num1 = null;
         double? num2 = 3.14157;
         double num3;
         num3 = num1 ?? 5.34;      
         Console.WriteLine(" Value of num3: {0}", num3);
         num3 = num2 ?? 5.34;
         Console.WriteLine(" Value of num3: {0}", num3);
         Console.ReadLine();

      }
   }
}
When the above code is compiled and executed, it produces the following result:
Value of num3: 5.34
Value of num3: 3.14157

No comments:

Post a Comment