CODEDIGEST
Home Articles CodeDigest Tutorials FAQs
Home > CodeDigest >  
Technologies
 


Nullables in Csharp : A Step Ahead Series
Submitted By Gaurav Arora
On 3/8/2009 9:21:15 PM
Tags: C#,CodeDigest  

Nullables in C#

Defiition:
Nullable types are instances if System.Nullable. A nullable type can represent the normal range of values of its underlying value type plus an additional null value.

Purpose:
The purpose of this code-snippet to describe the use of nullable types with little different of a general type.

Following Console code-block tells the all above :

/* This Example is a part of different

* * examples shown in Book:

* C#2005 Beginners: A Step Ahead

* * Written by: Gaurav Arora

* * Reach at : http://msdotnetheaven.com

* * File Name: nullable.cs */

using System;

using System.Collections.Generic;

using System.Text;

namespace AStepAhead.Nullable

{

class nullableclass

{

static void Main(string[] args)

{

int? num = null;

int? num1 = null;

if (num.HasValue == true)

{

Console.WriteLine("Num : {0}", num);

}

else

{

Console.WriteLine("Num has Null value");

}

//int y = num.GetValueOrDefault();

//throw an exception

int z;

try

{

//y = num.Value;

//Console.WriteLine("Y:{0}", y);

z = num1 ?? 2;

Console.WriteLine("Z:{0}", z);

}

catch(Exception ex)

{

Console.WriteLine(ex.Message);

}

Console.ReadLine();

}

}

}

 

Steps to test above:

  1. Open Console Window of available Visual Studio.
  2. Start - > Programs -> Visual Studio [version] ->Visual Studio Tools - >Console
  3. Now compile the abovefrom console as follow:

/>csc.exe nullableclass.cs

Above will produce an executable file nullableclass.exe, double click on this file.

Note :
You can also verify to uncomment above commented lines.

Recent Codes
  • View All Codes..