All Type Coding

Search Here

Nullable Types in c#

C# provides a special data types, the nullable types, to which you can assign normal range of values as well as null values.
Syntax:
< data_type> ? <variable_name> = null;

Here we will discuss
1. Nullable types in C#
2. Null Coalescing Operator ??  

In C# types  are divided into 2 broad categories.
Value Types  - int, float, double, structs, enums etc
Reference Types Interface, Class, delegates, arrays etc

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
By default value types are non nullable. To make them nullable use ?
int i = 0 (i is non nullable, so "i" cannot be set to null, i = null will generate compiler error)

int? j = 0 (j is nullable int, so j=null is legal)

Nullable types bridge the differences between C# types and Database types

Program without using NULL coalescing operator
using System;
class Program
{
    static void Main()
    {
        int a;
        int? b = null;

        if (b == null)
        {
            a = 0;
        }
        else
        {
            a = (int)b;
        }

        Console.WriteLine("The value of a={0}", a);
        Console.ReadKey();
    }
}
The Output will be:





The above program is re-written using NULL coalescing operator
using System;
class Program
{
    static void Main()
    {
        int a;
        int? b = null;

        //Using null coalesce operator ??
        a = b ?? 0;

        Console.WriteLine("The value of a={0}", a);
        Console.ReadKey();
    }
}

The Output will be same like above 

No comments :

Post a Comment