David Rutten
David Rutten

Reputation: 4806

Casting Generic Types

Public Function CastToT(Of T)(ByVal GenericType(Of Object) data) As GenericType(Of T)
   Return DirectCast(data, GenericType(Of T))
End Function

The above clearly does not work. Is there any way to perform this cast if I know that all objects inside data are in fact of Type T?

Upvotes: 2

Views: 1839

Answers (2)

SLaks
SLaks

Reputation: 887225

This is not possible, except for interfaces.

Upvotes: 2

EMP
EMP

Reputation: 61971

No, you cannot cast it directly. Presumably your GenericType is some kind of a container. You will just have to create a new instance of GenericType(Of T) and copy the contents into it, casting each object from Object to T. If GenericType was a System.Collections.List(Of T) then LINQ makes this very easy.

Upvotes: 1

Related Questions