Brandon Montgomery
Brandon Montgomery

Reputation: 6986

VB check for Null Reference when passing ByRef

I have a function that accepts a String by reference:

Function Foo(ByRef input As String)

If I call it like this:

Foo(Nothing)

I want it to do something different than if I call it like this:

Dim myString As String = Nothing
Foo(myString)

Is it possible to detect this difference in the way the method is called in VB .NET?

Edit

To clarify why the heck I would want to do this, I have two methods:

Function Foo()
  Foo(Nothing)
End Function

Function Foo(ByRef input As String)
  'wicked awesome logic here,  hopefully
End Function

All the logic is in the second overload, but I want to perform a different branch of logic if Nothing was passed into the function than if a variable containing Nothing was passed in.

Upvotes: 4

Views: 4755

Answers (2)

Adam Speight
Adam Speight

Reputation: 732

You could add a Null Reference check either:

1) prior to calling the function

If myString IsNot Nothing Then 
     Foo(myString)
End If

2) or inside the function

Function Foo(ByRef input As String)
    If input Is Nothing Then
        Rem Input is null
    Else
        Rem body of function
    End If
End Function

Upvotes: 0

Reed Copsey
Reed Copsey

Reputation: 564403

No. In either case, the method "sees" a reference to a string (input) which is pointing to nothing.

From the method's point of view, these are identical.

Upvotes: 6

Related Questions