tags:

views:

99

answers:

2

Hi,

I have the following statement, I want to turn it into a Public Shared Function :

If isEmployee Then

    Dim employeeInstance As New Employee
    employeeInstance = GetEmployeeInstanceByUserId(userId)
    Return employeeInstance 

Else

    Dim studentInstance As New Student
    studentInstance = GetStudentInstanceByUserId(userId)
    Return studentInstance 

End If

Public Shared Function GetWorkerInstance(Byval isEmployee as Boolean) As ...(not sure what to write here)...

There two possible return Type. I'm not sure what I should declare for the function return type.

Any suggestion? Thank you.

+2  A: 

This would be easiest if both the Employee and Student classes derived from one parent (either a base class or interface), then you could use that as your return type.

You can't declare different return types on the one function and you will not be able to create overrides that return different types, as the method signature resolution does not consider return types.

Oded
It's two different classes. These are the auto generated classes by LINQ.
Angkor Wat
You could change your method to be a generic one, with a generic return type (pass that in and cast the return type to it).
Oded
I'm putting it this way Public Shared Function GetWorkerInstance(Byval isEmployee as Boolean) As Object , so the Function caller need to cast it. What do you think?
Angkor Wat
Sure, but I don't see what that buys you. The caller knows that it wants an employee, since it is passing that information in, and then using that knowledge to perform the correct cast. It would be far better to have two functions that return an Employee and a Student, with the caller determining which function to call.
Jason Berkan
A: 

Generic

Private Class foo
    Dim s As String = "FOO"
End Class
Private Class bar
    Dim s As String = "BAR"
End Class
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim o As Object = GetWorkerInstance(True)
    If TypeOf o Is foo Then
        Stop
    Else
        Stop
    End If
End Sub
Public Shared Function GetWorkerInstance(ByVal isEmployee As Boolean) As Object
    If isEmployee Then Return New foo Else Return New bar
End Function
dbasnett