CType in VB.NET with dynamic second parameter (type)-Collection of common programming errors

If doesn’t make sense to cast an object to a variable type (a type that is unknown at compile time). The whole point of casting is to specify the exact type. I suspect, though, that rather than using a Type object, what you really need is a generic method or a generic class. For instance:

Public Function DoSomethingGenerically(Of T)(MyParameter As MyType) As T
    Return CType(MyParameter.MyProperty, T)
End Function

That’s a really pointless method, since all it does is cast the property and return it as that type, but it shows how you can cast to type T without knowing what, specifically, T happens to be. Then, you could call it like this:

Dim x As New MyType()
Dim y As MyType2 = DoSomethingGenerically(Of MyType2)(x)

That is precisely how the List(Of T) class, and other similar generic classes are implemented. Except, instead of making an individual method generic, they make the whole class generic, for instance:

Public Class MyList(Of T)
    Public Sub Add(item As T)
        ' ...
    End Sub
End Class