Friday, January 1, 2016

var keyword in C#

In today's blog post we will be discussing the var keyword in C#.

var Keyword

var keyword was introduced in C# 3.0. It is used for implicitly typed local variables. In any statement, if the compiler can decide the data type of the variable with no confusion, we can use the var keyword.


var keyword C#


For example,

var i = 12;       // will work

var j;   // will not work
j = 12;  //implicitly typed variables must be initialized

Since data type of variable j cannot be determined at the time of declaration, it won't compile and we can't use var keyword.

Another thing to note is that with the usage of the var type, the data type is fixed in the initialization statement itself. If we hover the mouse on the var keyword, we can see the data type that compiler is assigning the variable. We should not confuse it thinking that it's a dynamic type. In the first statement itself, the data type is fixed and we can't change the data type dynamically for the variable.

These two statements below are completely equivalent.,

var i = 12;   //implicit declaration

int i = 12;    //explicit declaration

They both produce the exact same IL code. That means that there is no performance effect with the usage of var keyword.

Why use var

Usage of var is more of a syntactic sugar. It makes the code a little shorter and mostly easier to read. For example, if we have some code like this:

ImageThumbnail thumbnail = new ImageThumbnail();


We can write it as:

var thumbnail = new ImageThumbnail();


This helps us remove a small part of the redundant code from the statement and thus reduce code noise.

Another and more important benefit of the var keyword is with anonymous types. So when we want to use an object without going through the hassle of declaring it's class (might make sense if we need to use that object only once), we can use this. For example,

var anonymousObject = new { Id = 1, Name = "Abhi" };

Console.WriteLine(anonymousObject.Name);


So here usage of var prevented me the hassle of creating a new class with 2 properties i.e. Id, Name.

Similarly, another common place where we use anonymous types is while using LINQ:
For example,

var p = from employee in employees
             where employee.Id == 1
             select new { employee.FirstName, employee.LastName };

So here the variable p is IEnumerable<> of anonymous type. Again, usage of var prevented me the hassle of creating a new class which I might not need else where in the code.

When to avoid var

Personally, I prefer to use var when it let's me reduce a few words of redundant code as we discussed earlier in the post. However, I don't like to use it where the data type might be unclear. For example,

var t = SomeMethod();


Here the method name is not telling me what it's returning. So I need to look at the method signature to determine what the data type of my variable is, which makes it less favorable to me. The compiler won't stop you from using it like this, it's a matter of personal preference and readability of the code.

Conclusion

So we saw how var keyword is only a syntactic sugar and does not lead to any performance difference. I use var for anonymous types as well as reducing a few words in the code, wherever possible.

For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)


2 comments:

  1. Worth mentioning, you cannot assign anonymous methods or lambdas. The following won't work.

    var act = () => Console.WriteLine("Hello World");

    Although this will:
    Action act = () => Console.WriteLine("Hello World");

    Do you know why?

    ReplyDelete
  2. Nice Question Phillip :) Because the compiler can't decide the type of right hand side. Here are a few examples: http://stackoverflow.com/questions/6897611/lambda-expression-and-var-keyword-in-c-sharp
    http://stackoverflow.com/questions/4965576/why-cant-an-anonymous-method-be-assigned-to-var

    ReplyDelete