Windows Phone Developers

Sunday, April 27, 2008

Nullable Type in Visual Basic.Net

Storing Null Values in VB.Net Variables

Most of times we use variables to store the response from the user; might be a simple message box. In that case, we would be using a boolean variable - one that can store True or False. What if the User didn't answer the question? It would be taken as False by default. To overcome this you can use the variable as Nullable. Now the var can have three states - True , False and Null

Sub Nullable_Example()

' Nullable type will be used to check if the value is assigned

Dim Answer As Nullable(Of Boolean)

Dim RetVal ' As MsgBoxResult

RetVal = MsgBox("Have you booked the ticket for olympics", vbYesNoCancel, "DotNetDud Examples")

If RetVal = vbYes Then

Answer = True

ElseIf RetVal = vbNo Then

Answer = False

End If

'Gets a value indicating whether the current Nullable<(Of <(T>)>) object has a value.

If Answer.HasValue Then

MsgBox("Question answered")

Else

MsgBox("Question not answered")

End If

' The above checks if the question is answered or not. Here the boolean variable answer can store True, False and Other


End Sub

You will get Error 'HasValue' is not a member of 'Boolean', if the variable is not declared as nullable (i.e., Dim Answer As Boolean)

Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

No comments:

Post a Comment

kbAlertz.com :: Visual Studio 2005

kbAlertz.com :: Visual Studio 2008

kbAlertz.com :: Visual Basic 2005