Senin, 16 Desember 2013

Computer Programming : Nullable types, Null coalescing operator in c# Programming

In Computer Programming, C# Data types are divided into two broad categories such as Value types and Reference type. In Value types, some inbuilt types such as int, float, double, structs, enum etc. These all are non-nullable types, it means these types don't hold null value. In other hand Reference types such as string, Interface, Class, delegates, arrays etc. can hold null value.
By default value types are non nullable. To make them nullable use, programmer have to use ?
  • int a=0   a is non nullable, so a cannot be set to null, a=null will generate compiler error
  • int ?b=0  b is nullable int, so b=null is legal

Operator Need

If programmer want to assign null value to non-nullable data types then there are some operators explained with an example. 

Lets take an simple example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int a;
            int? b = 100;
            a = b ?? 0;
            System.Console.WriteLine(a);
            Console.ReadKey();
        }
    }
}
Computer Programming : Nullable types, Null coalescing operator in c# Programming

Output show that if b hold some value like 100 then Null coalescing operator assign value to variable (a). If b hold null value then Null coalescing operator assign default value, which is zero to variable a. 

Replace the declaration of variable b with the following line:
            int? b = Null;
This will outputs zero (default value).

Tidak ada komentar:

Posting Komentar