Saturday, May 10, 2008

Local type inference

Local type inference is a language feature that allows you to define variables and use them without worrying about their true type. Local type inference is also interchangeably known as implicitly typed local variables. The burden is put on the respective language compiler to determine the type of a variable by inferring it from the expression assigned to the variable. The result is type safety while allowing you to write more relaxed code, which is required to support Language Integrated Query (LINQ).

Type inference can only be used within a local scope where its type can be inferred by the expression assignment. Type inference cannot be applied to any of the following:

* Cannot be a part of a member property declaration on a class, struct, or interface
* Cannot be used in a parameter list on a method
* Cannot be a return type for a method
* Cannot be defined without a right hand assignment expression
* Cannot reassign to be a different type once type has been inferred


namespace Sample.TypeInference
{
class Program
{
static void Main(string[] args)
{
int a = 5;
var b = a; // int
var x = 5.5M; // double
var s = "string"; // string
var l = s.Length; // int

Console.WriteLine("value of b is {0} and type is {1}",
b, b.GetType().ToString());
Console.WriteLine("type of x is {0}", x.GetType().ToString());
Console.WriteLine("type of s is {0}", s.GetType().ToString());
Console.WriteLine("type of l is {0}", l.GetType().ToString());

Console.ReadLine();
}
}
}

No comments: