Freigeben über


Using the .Cast() Extension Method

If you take a look at the set of extension methods offered on IEnumerable (and IEnumerable(Of T)), you'll find that there are plenty of very interesting extension methods. One of them is the Cast() extension method.

What does this extension method do? It provides a way to convert an IEnumerable(Of T) to an IEnumerable(Of U). Even more conveniently, it allows you to convert an IEnumerable to an IEnumerable(Of T).

Many pre-VS2005 frameworks do not take advantage of generic collection types (since they weren't invented then). As a result, if you have the following code, it may not do what you expect:

 Dim s = New ArrayList()
s.Add("String")
s.Add("two")
For Each c In s
    Console.WriteLine(c.ToUpper)
Next

If you compile this code with option strict on, you'll get an error saying that latebinding is not supported. Indeed, if you hover over the variable c, you'll notice that the type is object. Huh? I thought VB supported type inference?

VB in fact does support type inference, but because an ArrayList is essentially an IEnumerable of type object, the compiler does not know what element type to infer. Therefore, it infers object, since you can think of ArrayList as isomorphic to IEnumerable(Of Object).

You can tell the compiler that you really have an IEnumerable(Of T) by applying the Cast extension method like so:

 Dim s = New ArrayList()
s.Add("String")
s.Add("two")
For Each c In s.Cast(Of String)
    Console.WriteLine(c.ToUpper)
Next

And now, the compiler infers c as String, and you get your method, intellisense, etc. Sweet!

Be warned though : the elements of ArrayList better be strings! Or else Cast will throw an exception.

 

Technorati Tags: LINQ, VisualBasic, VB9

Comments