Nullables in C# - A Console Program

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 : 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.


Article by Gaurav Aroraa
Gaurav is a Microsoft Technology Specialist professional. He has awarded lifetime membership from Computer Society of India (CSI). He has more than 13yrs of experience in the industry. Currently, he is working in the capacity of Solution Architect with an MNC. He is serving to the various communities since 1999.

Follow Gaurav Aroraa or read 149 articles authored by Gaurav Aroraa

Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: