Type inference in Visual Basic (part 2)

Last time, I discussed a bit of the basics of type inference. Today, we’ll delve into it a little bit more to explore how type inference can make programming with Visual Basic a little more convenient.

Type inference can help you write less verbose code. You can imagine a function that returns say some generic type, and instead of typing:

dim x as MyGenericType(Of Integer, String, Integer) = CreateGenericType()

you can simply say:

dim x = CreateGenericType()

Remember that x’s type is really MyGenericType(Of Integer, String, Integer) so the usual things that you enjoy (Intellisense, tooltips, goto definition, etc) all work. This goes a long way in helping you write more concise code that is still type-safe, with no runtime performance penalties.

Also, some of the new LINQ features require this; in particular, when you create an anonymous type, or when you assign the result of a query comprehension to the variable, you do not in fact have any way to bind to the underlying type. Thus, type inference is necessary for these scenarios to work:

dim x = new with { .name = “tim” }

The type of x is compiler-generated; but in this case, intellisense (and all the nice UI features) still work, because x has a static type. There is actually no way to reference x’s type, and thus, no way to pass x to functions, etc, except through late binding. More on this in a later post.

Additionally, when you create a query, you want to use type inference, because you may not be able to figure out what the type of the query is that gets returned:

dim q = from c in Customers where c.age > 10 select c.firstname, c.lastname

In this case, q is an IEnumerable of an anonymous type with the fields firstname and lastname. You couldn’t even specify this return type if you wanted to!

Finally (for this post) for loops are much nicer with this feature. You can now say:

for each e in q
    Console.WriteLine( e.firstname & ” ” & e.lastname )

The compiler will automatically type e to the element type of the collection in q. This saves you much typing, and will produce code that just looks a lot cleaner.

I hope that you have had a chance to play with the latest CTP! Feel free to let me know if you have any questions about the features; I try to hang out in the forums once in a while as well!

Comments (1)

  1. says:

    Eines der neuen Features von VB9 und C# 3.0 sind " Implicitly Typed Local Variables ". Bei diesem Feature