Skitzafreak
Skitzafreak

Reputation: 1917

Return Null Reference in VB.Net

I have the following method in my program:

Public Function AddHandlerTo(ByVal compName As String) As System.Object
    For Each item In componentList
        If item.Name.Equals(compName) Then
            AddHandlerTo = item
        End If
    Next
End Function

As expected, because of how my Return statement is nested I am getting a warning in my compiler:

Function 'AddHandler' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.

Now the purpose of this method is to help me (as the method name says) add handlers to specific objects that aren't easily accessible. Essentially, each item in the componentList is a different child of the same parent object. Regardless, it doesn't really matter for my question here.

I am trying to figure out how to add a final Return statement to the end of the method so that I no longer get the error. If there is no object in the loop that matches the criteria, I want it to return an exception that no object exists or something like that. Though I don't know how exactly to accomplish this, and my ability to find help via Google is apparently horrendous.

Upvotes: 0

Views: 1286

Answers (1)

LarsTech
LarsTech

Reputation: 81610

I typically always use a return statement like this:

Public Function AddHandlerTo(ByVal compName As String) As System.Object
  Dim result As Object = Nothing
  For Each item In componentList
    If item.Name.Equals(compName) Then
        result = item
    End If
  Next
  Return result
End Function

or

Public Function AddHandlerTo(ByVal compName As String) As System.Object
  For Each item In componentList
    If item.Name.Equals(compName) Then
        Return item
    End If
  Next
  Return Nothing
End Function

Where ever you are calling this function, you would check to see if it returned something or nothing.

Upvotes: 3

Related Questions