BT

Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ

Topics

Choose your language

InfoQ Homepage News Mono Adds Support For Type Inference in C#

Mono Adds Support For Type Inference in C#

Marek Safar has announced that the C# 3.0 compiler for Mono now supports implicitly typed local variables and implicitly typed arrays using a technique known as type inference.

In C-based languages like C#, it is common to use the redundant "type variable = new type" pattern. When the type names are long or are changed frequently, this can become quite tedious.

C# 3.0 eliminates much of this redundancy by introducing the "var" keyword. This allows developers to omit the variable type without sacrificing static typing. The compiler determines the correct type based on the static type of the expression to the right of the equals sign.

A key point here is that C# is still early-bound and statically typed. This does not open up C# developers to the kinds of problems associated with late binding in Visual Basic such as missing method exceptions caused by spelling errors.

While nice to have, type inference was not added just to make typing a bit faster. It is a necessary feature for anonymous classes, which are heavily used by LINQ. Since anonymous classes do not have a name, there is no way to create variables of their type in C# without type inference. (VB does with late binding, but again that opens the possibility for missing method exceptions.)

There are two type inference features supported by C#. Implicitly typed variables and implicitly typed arrays. Both work fundamentally the same way, at compile time the keyword "var" is replaced with the correct scalar or array type for the associated expression.

Type inference is not allowed in cases where the variable is not assigned a value on the same line it is declared. While this is technically possible, it would introduce a level of complexity that the C# compiler team probably does not want to address.

Marek Safar mentions two other areas where type inference is not allowed.

Also as the name says, implicitly typed local variable, you cannot use var for field declaration or constant variables, therefore following declarations will both produce a compiler error.

I am not sure why there are such limitations but I am probably missing something.

Note: Technically speaking, anonymous classes have names that are generated by the compiler. However, the names are not necessarily predictable and should be considered an implementation detail. Or in other words, it is safer to pretend they do not have them at all.





Rate this Article

Adoption
Style

BT