BT

Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ

Topics

Choose your language

InfoQ Homepage News Var/Option Infer: New Syntax for C# and VB 9

Var/Option Infer: New Syntax for C# and VB 9

Microsoft is considering several new language features for C# 3.0 and Visual Basic 9 including type inference. As this may result in breaking changes, a new mode called Option Infer is also being considered for VB.

With Option Infer turned on, VB developers will be able to use type inference for variable declarations. Type inference allows developers to omit type declarations without resorting to late binding. This reduces the amount of code while not giving up the advantages of early (a.k.a. static) binding and compile-time type checking.

Consider this code:

Dim name As String = "John Doe"
Dim age As Integer = 24
Dim gender As Gender = Gender.Male
Dim weight As Decimal = 1.8

In each line, the compiler knows what type the variable is. Unfortunately, developers still have to explicitly type it out to if they want to use strict type checking. With VB 9, developers may be able to save a bit of code by writing this:

Dim name = "John Doe"
Dim age = 24
Dim gender = Gender.Male
Dim weight = 1.8

With Option Infer off, each of these variables will be compiled as type Object. When Option Infer is turned on, the compiler will determine the correct type based on the r-value. If a wider or narrower type is needed, developers can still override this behavior using the As clause.

This also gives rise to a new use of the Dim keyword in For-Each loops.

For Each Dim employee In EmployeeList
 Console.WriteLine(employee.FullName)
Next

While the syntax looks a little awkward, it does allow one to omit the loop variable's type when using strongly typed enumerators. As an additional bonus, changing the contained in EmployeeList does not necessarily mean every for-each loop that accesses it will need to be altered.

C# will also gain type inference, but the syntax is slightly different to account for its C ancestry. A new keyword, var, is used in place of the explicit type.

var name = "John Doe";
var age = 24;
var gender = Gender.Male;
var weight = 1.8;
foreach (var employee in EmployeeList) {
 Console.WriteLine(employee.FullName);
}

This will not result in a breaking change for most C# applications and thus will not need a compiler option. A warning will appear if the application uses a type named "var".

A preview of Visual Studio is available via Virtual PC image. Currently it doesn't support all of the proposed language enhancements, so some of these examples may not in the latest CTP.

Rate this Article

Adoption
Style

BT