Why Var Keyword Is Frequently Used In C#

What is var in C#

Var is nothing but an implicit type which we use as a shortcut to define the type of variable or object instantly and it is very nice feature in C#. In other words, var is an implicit type that allows you to write shorter and more readable code which defines the alias of actual type which does not have any performance penalty where compiler takes care to define actual type in IL.

However, there is a misunderstanding behind var which is that the developer uses var with every line of code to define the type but the actual purpose of var keyword is where developer is not sure about actual return type of method and wanted to finish the line without stepping into the method to know the return type or wants to deal with anonymous type of data.

Var as a shortcut

The frequent use of var is as a shortcut without knowing any technicality of programming lines. The underlying idea behind shortcut is that compiler will decide the actual type at the time of compilation and in IL will get correct strongly typed data type.

var number = 1212;

quicwatch

  1. var stream = new System.IO.StreamWriter("c:\\test.txt");  
quickwatch

It means compiler will set the correct data type based upon the data to be assigned.

var as a requirement

The actual purpose of var keyword is to hold something which is anonymous type and we see anonymous type frequently in LINQ or while creating anonymous type object.
  1. var person = new { Name = "Smith", Address = "USA" };  
quickwatch

Restriction on using var

There are some restrictions on how to use var they are,

 

  • var is only applicable under local scope where declaration and initiation are in the same place.

    Since compiler has to know data type immediate based upon data to be assigned. If the variable is not immediately assigned then compiler will throw an error.

  • var cannot be used at class or global level.

  • var cannot be used in initialization expression,

    Wrong Right
    var num = (num=20);//Worngint numOne = (numOne = 50);//Right
    var stream = null;
    using(stream = new System.IO.StreamWriter("c:\\Personal\\test.txt"))
    {}
    using(var stream = new System.IO.StreamWriter("c:\\Personal\\test.txt"))
    {}

Advantage

  • Focus on readability of code
  • Helpful when tedious to type specific type of variable
  • Easy to work on anonymous type


Similar Articles