Local Variable Type Inference

Local Variable Type Inference

Local variables can be given an inferred “type” of var instead of an explicit type. The var keyword instructs the compiler to infer the type of the variable from the expression on the right side of the initialization statement. The inferred type may be a built-in type, an anonymous type, a user-defined type, or a type defined in the .NET Framework class library

With this feature, the type of the local variable being declared is inferred from the expression used to initialize the variable. This is achieved using the var keyword (familiar to those who work with scripting languages, but actually it is quite different). It allows us to write the following code:

 

var num = 50; 
var str = "simple string";
var obj = new myType();
var numbers = new int[] {1,2,3};
var dic = new Dictionary<int,myType>();

The compiler would generate the same IL as if we compiled:

int num = 50; 
string str = "simple string";
myType obj = new myType();
int[] numbers = new int[] {1,2,3};
Dictionary<int,myType> dic = new Dictionary<int,myType>();

Note that there is no un-typed variable reference nor late-binding happening, instead the compiler is inferring and declaring the type of the variable from the right-hand side of the assignment. As a result, the var keyword is generating a strongly typed variable reference.

Automatic Properties C#

[dropcap]A[/dropcap]utomatic properties used as a shorter way of defining a simple property which just sets and gets the value of a private member variable. Consider the following Code;

public class Point
 {
    private int _x, _y;
    public int X
    {
        get
        {
          return _x;
        }
        set
        {
          _x = value;
        }
    }
    public int Y
    {
        get
        {
          return _y;
        }
        set
        {
          _y = value;
        }
    }
}

The above code simply defining a class with basic properties. Now with the new C# compiler in Visual Studio .NET, we can write a shorter cleaner version using Automatic Properties which automatically generates the private fields with get/set operations :

public class Point
{
    public int X { get; set; }
    public int Y { get; set; }
}

The code above is even more readable and less verbose.
Note that this feature has nothing to do with LINQ. I just thought it would be appropriate to list it with the other new language features.

 

For more information see MSDN C# Programming Guide