2

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)?

Daniel
  • 10,864
  • 22
  • 84
  • 115

2 Answers2

1

It is not possible to use an extension method for an object type (it should be another type) VB.NET: impossible to use Extension method on System.Object instance. A module with extension methods has to be imported so you can use:

ReadOnly Property NodeID As Integer
  Get
    Return ToIntegerOrDefaultSession(SessionVariables.SELECTED_NODE_ID))
  End Get
End Property

Alternatively you can rewrite the extension method

<System.Runtime.CompilerServices.Extension()> _
Public Function ToIntegerOrDefault(Sess As HttpSessionState, KeyOFvalueToParse As String, Optional ByVal defaultValue As Integer = 0) As Integer
  Dim retVal As Integer = 0
  If Not Integer.TryParse(Sess(KeyOFvalueToParse).ToString, retVal) Then
    retVal = defaultValue
  End If
  Return retVal
End Function

And call

Session.ToIntegerOrDefault(SessionVariables.SELECTED_NODE_ID)

Or define extension method for String and call

Cstr(Session(SessionVariables.SELECTED_NODE_ID)).ToIntegerOrDefault()
Community
  • 1
  • 1
IvanH
  • 5,039
  • 14
  • 60
  • 81
0

Give Session a default value when you declare it. If it's a list using the new keyword will do the trick. If it's something else you'll have to show what it is.

tinstaafl
  • 6,908
  • 2
  • 15
  • 22
  • It would be nice if you provided an example of how to do it. – Victor Zakharov May 29 '13 at 19:19
  • How do you provide an example on initializing a collection, when the OP doesn't say what the collection is? Just off the top of my head I can come up with half a dozen different collections. – tinstaafl May 29 '13 at 19:23
  • Hi there. The extension method accepts an object, attempts to parse it as an integer, then returns the parsed value (or if it fails, returns the optional default). There are no collections. – Daniel May 29 '13 at 19:50