CrispinH
CrispinH

Reputation: 2059

Casting to List(Of T) in VB.NET

In C# it's possible to cast to List<T> - so if you have:

List<Activity> _Activities;
List<T> _list;

The following will work:

_list = _Activities as List<T>;

but the translated line with VB.NET which is:

_list = TryCast(_Activities, List(Of T))

throws a compilation error. So I've had a good hunt around and experimented with LINQ to find a way round this to no avail. Any ideas anyone?

Thanks

Crispin

Upvotes: 5

Views: 32827

Answers (3)

Hans Passant
Hans Passant

Reputation: 941397

I repro, this should technically be possible. Clearly the compiler doesn't agree. The workaround is simple though:

    Dim _Activities As New List(Of Activity)
    Dim o As Object = _Activities
    Dim tlist = TryCast(o, List(Of T))

Or as a one-liner:

    Dim tlist = TryCast(CObj(_Activities), List(Of T))

The JIT compiler should optimize the temporary away so it doesn't cost anything.

Upvotes: 7

Jay Riggs
Jay Riggs

Reputation: 53593

You can use the generic List.ConvertAll method.

Given a List the method will return a List of a different type using a converter function you supply.

The MSDN article I linked has an excellent example.

Upvotes: 1

Nate
Nate

Reputation: 30636

I always use DirectCast(object, type)

Upvotes: 0

Related Questions