I've created the following extension method:
<System.Runtime.CompilerServices.Extension()> _
Public Function ToIntegerOrDefault(ByVal valueToParse As Object, Optional ByVal defaultValue As Integer = 0) As Integer
Dim retVal As Integer = 0
If Not Integer.TryParse(valueToParse.ToString, retVal) Then
retVal = defaultValue
End If
Return retVal
End Function
and I'd like to use this extension method on session variables like so:
ReadOnly Property NodeID As Integer
Get
Return Session(SessionVariables.SELECTED_NODE_ID).ToIntegerOrDefault()
End Get
End Property
However, upon invoking the method before the session variable has been set, a NullReferenceException
is thrown with message Object variable or With block variable not set.
Is there a safe way to utilize an extension method on a session variable in this way (given that the session variable may be null)?