Best Industrial Training in C,C++,PHP,Dot Net,Java in Jalandhar

Wednesday 26 December 2012

Nullable types

Nullable types

Value types cannot be assigned a null literal. Reference types can. Applications that work with databases deal with the null value. Because of this, special nullable types were introduced into the C# language. Nullable types are instances of the System.Nullable<T> struct.
using System;

class CSharpApp
{
    static void Main()
    {
        Nullable<bool> male = null;
        int? age = null;

        Console.WriteLine(male.HasValue);
        Console.WriteLine(age.HasValue);
    }
}
A simple example demonstrating nullable types.
Nullable<bool> male = null;
int? age = null;
There are two ways how to declare a nullable type. Either with the Nullable<T> generic structure, in which the type is specified between the angle brackets. Or we can use a question mark after the type. The latter is in fact a shorthand for the first notation.
$ ./nullabletypes.exe 
False
False
Output.

No comments:

Post a Comment