1. What does local type inference mean?
2. Advantages of using local type inference?
3. What are the cases when the var keyword is not allowed?
The C# compiler is able to determinate a variable type inferring it from the assignment expression.
1. Better performance. Using local type inference we can avoid boxing/unboxing.
2. Type safety. When we use local type inference the C# compiler is able to check type in the compile time.
Example 1:
static void Main(string[] args)
{
var x = args;
Trace.WriteLine(x.GetType());
var y = default(string);
y = "";
Trace.WriteLine(y.GetType());
var a = 1;
Trace.WriteLine(a.GetType());
var b = 1.1;
Trace.WriteLine(b.GetType());
var c = a / b;
Trace.WriteLine(c.GetType());
var d = "string";
Trace.WriteLine(d.GetType());
}
Output:
System.String[]
System.String
System.Int32
System.Double
System.Double
System.String
Example 2:
class Program
{
//The contextual keyword ‘var’ may only appear within a local variable declaration
var x = 0;
//The contextual keyword ‘var’ may only appear within a local variable declaration
public static var ReturnVar() { return 0; }
//The contextual keyword ‘var’ may only appear within a local variable declaration
public static void ReturnVar(var param) { }
static void Main(string[] args)
{
//Implicitly-typed local variables must be initialized
var x;
//Cannot assign <null> to an implicitly-typed local variable
var t = null;
}
}