Nullable(Of Type) and converting to value type

Category VB.Net Sub Category Manipulating Types
Bookmark and Share
How to convert between these types in code.
In this example the RefNo property is held as a nullable type of integer.

Copy Code
Public Property RefNo() As Nullable(Of Integer) Get If IsNothing(Session("RefNo")) Then Return Nothing Else Return CInt(Session("RefNo")) End If End Get Set(ByVal value As Nullable(Of Integer)) Session("RefNo") = value End Set End Property


To pass this RefNo property value into the ValidRefNo integer variable, use the following code snippet to perform this.

Copy Code
Dim ValidRefNo as Integer If RefNo.HasValue Then ValidRefNo = RefNo.Value Else ValidRefNo = 0 End If


Other examples of using the nullable type in code:

Copy Code
Dim i As Nullable(Of Integer) Dim b As Boolean i = Nothing b = i.HasValue 'Will be False i = 123 b = i.HasValue 'Will be True Dim j As Integer = i.Value 'j = 123
Share the love
Bookmark and Share