views:

52

answers:

3

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

A: 

I always use DirectCast(object, type)

Nate Bross
A: 

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.

Jay Riggs
+1  A: 

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.

Hans Passant
Wouldn't it be easier to just throw an `InvalidCastException`?
Ben Voigt
This seems to have done the trick. I'm following through Julie Lerman's Entity Framework book and there's a bit more work to be done before I have running code.
CrispinH