Nullable Types which was introduced in the .NET framework 2.0 give the developer the option of storing null values in a Value Type variable.
This Will allow you to create an object which holds Null value.
This comes handy when you want an null value to be stored in an Object.
VB.NET CODE
Private Name As String
Private isWorking As Boolean
Private sal As Nullable(Of Integer)
Sub EnterDetails(ByVal n As String, ByVal wor As Boolean, ByVal sals As Nullable(Of Integer))
Name = n
isWorking = wor
If isWorking = True Then
sal = sals
Else
sal = Nothing
End If
End Sub
Sub ShowDetails()
Console.WriteLine("Name : " & Name)
Console.WriteLine("IsWorking : " & isWorking)
If (sal.HasValue = True) Then
Console.WriteLine("Sal : " & sal.ToString())
Else
Console.WriteLine("Sal : N.A")
End If
End Sub
To use This class
Sub Main()
Dim i As New Emp
i.EnterDetails("HEFIN", True, 124214)
i.ShowDetails()
End Sub
In C# we create Nullable Types by using the < > brackets.
C# Code
This Feature of .net framework 2.0 can be used to use an object of any type to hold a null value.
class Employee
{
private string Name;
private bool isWorking;
private Nullable< int > sal;
public void enterDetails(string na,bool Working,Nullable< int > salary)
{
this.Name = na;
this.isWorking = Working;
if (isWorking == true)
{
sal = salary;
}
else
{
sal = null;
}
}
public void GetDetails()
{
Console.WriteLine("Name : " + this.Name);
Console.WriteLine("IsWorking : " + this.isWorking);
if (this.sal.HasValue == true)
{
Console.WriteLine("Salary : " + this.sal);
}
else
{
Console.WriteLine("Salary : N.A");
}
}
}
Using this object in another class
class usingNull
{
static void Main(string[] args)
{
Employee emp = new Employee();
emp.enterDetails("HEFIN", true, 10090);
emp.GetDetails();
emp.enterDetails("ONEMORE", false, null);
emp.GetDetails();
}
}
================================================================================
Regards Hefin Dsouza.