Mar 25, 2009

Local Type Inference in C# 3.0

There are list of new features added in C# 3.0, I already cover Automatic Properties, and Object-Collection Initialization and Partial Methods in my older posts, here one more new feature which allow you to write more relaxed code. In another work you can define variable and use them without worrying about too much about their type, leaving it to the compiler to determine the correct type of a variable by inferring it from the expression assigned to the variable itself.

The price for using type inference might be less explicit code against the types you want to use, but in our opinion, this feature simplifies code maintenance of local variables where explicit type declaration is not particularly meaningful.

This might seem to be equivalent to defining a variable of type object, but it is not. The following code shows you that an object type requires the boxing of a value type (see b declaration), and in any case it requires a cast operation when you want to operate with the specific type (see d assignment):

var a = 2;       // a is declared as int
object b = 2; // Boxing an int into an object
int c = a; // No cast, no unboxing
int d = (int) b; // Cast is required, an unboxing is done

C# 3.0 offers type inference that allows you to define a variable by using the var keyword instead of a specific type. When var is used, the compiler infers the type from the expression used to initialize the variable.

The var keyword calls to mind the Component Object Model (COM) type VARIANT, which was used pervasively in Visual Basic 6.0, but in reality it is absolutely different because it is a type-safe declaration. The following code shows some examples of valid uses of var: x, y, and r are double types; d and w are decimal; s and p are string; and l is an int. Please note that the constant 2.3 defines the type inferred by three variables, and the default keyword is a typed null that infers the correct type to p.

public void ValidUse(decimal d)
var x = 2.3; // double
var y = x; // double
var r = x / y; // double
var s = "sample"; // string
var l = s.Length; // int
var w = d; // decimal
var p = default(string); // string

The next sample shows some cases in which the var keyword is not allowed:

class VarDemo
// invalid token 'var' in class, struct or interface member declaration
var k = 0;
// type expected in parameter list
public void InvalidUseParameter(var x) { }
// type expected in result type declaration
public var InvalidUseResult()
return 2;
public void InvalidUseLocal()
var x; // Syntax error, '=' expected
var y = null; // Cannot infer local variable type from 'null'
// …

The k type can be inferred by the constant initializer, but var is not allowed on type members. The result type of InvalidUseResult could be inferred by the internal return statement, but even this syntax is not allowed .

No comments: