< Browse > Home / Programming / Blog article: var Keyword In C#

| RSS

var Keyword In C#

January 6th, 2009 | 2 Comments | Posted in Programming

I have a confession to make. When I saw var keyword for the first time I did not like it at all. My first opinion was that var was so variant like. Call me a control freak but I like to clearly see what I am declaring. And var was something I thought made the code less readable. However since I started working with LINQ I got into a habit of using var. I realised that it makes my life easy by letting the compiler figure things out for me. So in this post I will pay due respect to var keyword.

Anything declared using var keyword is implicitly typed which means that compiler will determine the correct type based on what the variable is initialised to. Here I am declaring three variables x, y and z. All of them are initialised to different values which are also of different Types such as DateTime, string and List<T>.

var x = DateTime.Now;
 
var y = "Hello";
 
var z = new List<String>();

Let’s examine the IL to verify that x, y and z are of Types they have been initialised to.

image

Here you can see that x is of valuetype, y is a string and z is of type List<string>.

I find this as neat little syntax sugar to which I have become addicted.

Keep in mind that you cannot write a statement like this.

var x;

 

This will give an error while compiling. And it makes sense because the compiler does not know which Type it should consider x as.

Compiler Error






Leave a Reply 1026 views, 3 so far today |
Tags: ,
Follow Discussion

2 Responses to “var Keyword In C#”

  1. Json Says:

    But really…what’s the point of using var on something of known type? Like you said, var is specialized for dynamic frameworks and languages like Lambda and LINQ, where you don’t know what’s coming back.

    When you do something like:
    var myName = “Json”; //what tha hell is the point of this?

    It DOES make code hard to read when var is applied out of context.
    There is no logical reason not to put:
    string myName = “Json”;

    You don’t buy anything beneficial from using var for KNOWN data types. Because on the right side of the equal sign guess what, you KNOW the data type. It’s silly…

  2. Deepak Says:

    Jason,

    I could not agree more with you. You have to use var judiciously. It adds most value when working with anonymous types. I do not have problems using var once in a while but I stay away from using it for every declaration.

Leave a Reply