ExtensionMethod.NET Home of 818 C#, Visual Basic, F# and Javascript extension methods

ToNullableString()

Calling Value.ToString on a Nullable(Of T) type where the value is null will result in an "Nullable object must have a value." exception being thrown. This extension method can be used in place of .ToString to prevent this exception from occurring.

Source

<Extension()> _
Public Function ToNullableString(Of T As Structure)(ByVal param As Nullable(Of T)) As String
	If (Not param.HasValue) Then
            Return String.Empty
        Else
            Return param.Value.ToString
        End If
End Function

Example

Dim value as System.Nullable(Of Byte) = GetValueFromDatabase()

Textbox1.Text = value.ToNullableString()

' GetValueFromDatabase is simulating retrieving a System.Nullable(Of Byte) value from the database.

Author: Chris Rock

Submitted on: 31 mrt 2008

Language: VB

Type: System.Nullable<T>

Views: 2880