Friday, 27 July 2012

Nullable Types In C#


Nullable Types

Nullable types represent value-type variables that can be assigned the value of null.
Nullable types are declared in one of two ways:
System.Nullable<t> variable
-or-
T? variable
T is the underlying type of the nullable type. T can be any value type including struct; it cannot be a reference type.
In many programming applications, where there is database interactions, variables can exist in an undefined state. For example, a field in a database may contain the values true or false, but it may also contain no value at all. Similarly, reference types can be set to null to indicate that they are not initialized.
The nullable type modifier enables C# to create value-type variables that indicate an undefined value.
Example - Nullable Types
using System;
public struct Prime
{
public int PrimeNum;
public Prime(int num)
{
PrimeNum = num;
Console.WriteLine(num);
}
}
class PrimeNumbers
{
static void Main(string [] args)
{
Prime? objPrime = new Prime?(new Prime(5));
}
}

System.Nullable<>


using System;
using System.Collections.Generic;
using System.Text;
namespace School
{
class nullType
{
static void Main(string[] args)
{
System.Nullable<int> numOne = 34;
System.Nullable<int> numTwo = null;
System.Nullable<int> res = numOne + numTwo;
if (res.HasValue == true)
Console.WriteLine(res);
else
Console.WriteLine("Result Null");
}
}
}

Converting Nullable Types. Implicit Conversion

using System;
class ImplicitConversion
{
static void Main (string [] args)
{
int? numOne = null;
if (numOne.HasValue == true)
{
Console.WriteLine("Value of numOne before conversion: " + numOne);
}
else
{
Console.WriteLine ("Value of numOne: null");
}
numOne = 20;
Console.WriteLine("Value of numOne after implicit conversion: " + numOne);
}
}

Converting Nullable Types : Explicity Conversion

using System;
class ExplicitConversion
{
static void Main (string [] args)
{
int? numOne = null;
int numTwo = 20;
int? resultOne = numOne + numTwo;
if (resultOne.HasValue == true)
{
Console.WriteLine("Value of numOne before conversion: " + resultOne);
}
else
{
Console.WriteLine ("Value of resultOne: null");
}
numOne = 10;
int result = (int) (numOne + numTwo);
Console.WriteLine("Value of result after explicit conversion: " + result);
}
}

Boxing Nullable Types

using System;
class Boxing
{
static void Main (string [] args)
{
int? number = null;
object objOne = number;
if (objOne != null)
{
Console.WriteLine("Value of object one : " + objOne);
}
else
{
Console.WriteLine ("Value of object one: null");
}
double? value = 10.26;
object objTwo = value;
if (objTwo != null)
{
Console.WriteLine("Value of object two: " + objTwo);
}
else
{
Console.WriteLine("Value of object two: null");
}
}
}



No comments:

Post a Comment