Tuesday 21 January 2014

Nullable Types in C#

                                                                                                                                       Precious......
                                                                                                                                                    Next......

Nullable-: We can directly assign NULL value to the reference Type But can't assign null value to Value type so we use Nullable keyword to assign NULL value to value type variable.
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


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 AvailableTickets;
        int? TicketsOnSale = null;
        if (TicketsOnSale == null)
        {
            AvailableTickets = 0;
        }
        else
        {
            AvailableTickets = (int)TicketsOnSale;
        }
        Console.WriteLine("Available Tickets={0}", AvailableTickets);
    }
}


The above program is re-written using NULL coalescing operator
using System;
class Program
{
    static void Main()
    {
        int AvailableTickets;
        int? TicketsOnSale = null;
        //Using null coalesce operator ??
        AvailableTickets = TicketsOnSale ?? 0;
        Console.WriteLine("Available Tickets={0}", AvailableTickets);
    }
} 



                                                                                                                                       Precious......
                                                                                                                                                    Next......

No comments:

Post a Comment

C# program Selection Sorting

Selection sort is a straightforward sorting algorithm. This algorithm search for the smallest number in the elements array and then swap i...