.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Articles >> .Net Framework >> Post New Resource Bookmark and Share   

 Subscribe to Articles

Using Nullable Type in .NET Framework 2.0 VB.NET/C#

Posted By:Hefin Dsouza       Posted Date: August 12, 2009    Points: 25    Category: .Net Framework    URL: http://www.dotnetspark.com  
 

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.

 Subscribe to Articles

     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend