tags:

views:

25

answers:

3

Is it possible to have an argument of any type? Here's what i mean:

some_function(argument)
    if (argument type is string)
        do something with a string
    else if (argument type is datarow)
        do something with a data row
    ...

I've found something about generics, but i'm not sure if it's what i want.

A: 

one way is that you can use base type. Set the argument as Object.

some_function(argument as Object)
if (argument type is string)
    do something with a string
else if (argument type is datarow)
    do something with a data row
Arseny
I guess it's a good idea, since i'll only pass in object descendant types. All i need now is a way to check the type and cast the object, but that's something google should help me with so thanks for the tip.
Marius S.
+1  A: 

You can totally do it like this:

Sub DoSomething(ByVal arg As Object)
    If TypeOf arg Is TypeX Then
        DoSomethingX(DirectCast(arg, TypeX)
    ElseIf TypeOf arg Is TypeY Then
        DoSomethingY(DirectCast(arg, TypeY))
    End If
End Sub

But: at least first ask yourself if you're trying to do what should really be done with inheritance and polymorphism.

That's a big word for basically this:

Public MustInherit Class BaseType
    Public MustOverride Sub DoSomething()
End Class

Public Class TypeX
    Inherits BaseType

    Public Overrides Sub DoSomething()
        ' Whatever TypeX does. '
    End Sub
End Class

Public Class TypeY
    Inherits BaseType

    Public Overrides Sub DoSomething()
        ' Whatever TypeY does. '
    End Sub
End Class

It looks like a lot of typing, but then down the road any time you have an object of type BaseType, instead of a bunch of If/ElseIf checks, you just do:

arg.DoSomething()

Might not be the solution in your case. Just wanted to point out that this exists, and might be a better solution to your problem (hard to say without details).

Dan Tao
Inheritance would be nice, sure, but this is not the case in which i can do that. Thanks for the example!
Marius S.
Better to use overloading, rather than `TypeOf Is` ? As in my answer :)
MarkJ
@MarkJ: That does not work if the parameter is typed as `Object` in code.
Dan Tao
A: 

Just use overloading. Create methods that have the same name but different argument lists. Visual Basic .NET figures out which method to call during compile based on the parameter types that you pass.

  Sub some_function(ByVal argument As String)

  End Sub
  Sub some_function(ByVal argument As DataRow)

  End Sub
MarkJ