Local Type Inference – var keyword

Type Inference is one of the important features for a dynamic language; it preserves type safety while allowing you to write code with more ease. The compiler has the built-in intelligence to determine the “Type” of a variable. 
There is always an argument about code readability when it comes to dynamic type inference, but when we work with external APIs and language features like LINK this becomes very handy tool, and it helps us to keep up with the design principle “Program to an Interface, not an implementation” 
The keyword “var” is used to denote the complier that you are declaring a dynamic type inference variable.

var i = 0;
is equivalent to
int i = 0;

The var keyword should not be mistaken with the VB6 Variant keyword or the .netObject keyword, C# is highly type safe, when the compiler converts the code into MSIL var is replaced with the real type, to prove this try running the code mentioned below

using System;
class Program
{
    public static void Main()
    {
        var i = 0;
        var assemblies = AppDomain.CurrentDomain.GetAssemblies();
 
        Console.WriteLine(i.GetType().Name);
        Console.WriteLine(assemblies.GetType().Name);
    }
}
 
Output:
Int32
Assembly[]

We should name our variables meaningfully when we use the var keyword or else the readability of the code will be affected in a very bad way

Valid Usage

we can assign constants, expression and methods with return type other than void to a variable declared with the var keyword, the var key word can be used only within a local scope, these are some valid usage

var x = 1;
var y = x;
var r = x % y;
var s = “Hello World”;
var l = s.Length;
var b = default(bool);

Invalid Usage

  • The cannot be used to declare a class level variable
  • It cannot be used as a return type for a method
  • It cannot be used to define the type of a method parameter
  • It cannot be used without assigning a value to the variable
  • It cannot be used if you assign null to a variable
class MyClass
{
    var k = 0; // cannot be used to declare a class level variable
 
    public void MyMethod( var x ) {} // invalid parameter type
 
    public var Mymethod() {return false;} // invalid return type
 
    public void MyMethod()
    {
        var x; // Syntax error, ‘=’ expected
        var y = null; // Cannot infer local variable type from ‘null’
    }
}