Saturday, January 17, 2009

C# Type Inference

C# 3.0 introduced a new language concept called Type Inference. Here is an example:

var n = 3;

Instead of specifying a type in this variable declaration the keyword var is used. When this line is compiled the compiler will determine the appropriate data type for the variable based on the initial value assigned to it. In this case ‘n’ will be an Int32. I think ‘var’ was an unfortunate choice for this keyword since it brings to mind Variants from VB6. Variants changed type based on what was assigned to them, but this is not the case with var. Variables declared with var are strongly typed but the compiler determines the type, not the programmer. The following code will not compile:

var n = 3;

n = “test”;

This will produce the error “Cannot implicitly convert type 'string' to 'int'”.

You can also use var to declare arrays like this:

var nums = new[] {0, 1, 2};

This will result in an array of Int32. Note that when arrays are declared every element has to be of the same type. For example this line will produce a compiler error:

var nums = new[] { 0, "test", 2 };

There are a couple limitations to using var.

- var can only be used for local variables and cannot be used at the class level.

- The variable has to be initialized in the same line as it is declared. You cannot do:

var n;

n = 1;

-You cannot define multiple variables at one time using var. This is not legal:

var n = 3, x = 2;

When you look at this feature and some of the other new features introduced in C# 3.0 they may appear of limited use and pretty random. Although these features do have their uses the main purpose is to support a major new feature in 3.0, Language Integrated Query (LINQ). I will talk about this in a later blog post.

No comments: