Using var keyword in C#

Keyword var is cool thing we can use to make our code more readable for other programmers and why not – reviewers. But var can also be used to make our code difficult to understand. In this case, lte’s say, we are overusing var. So, var is like wine – if one takes glass of it then everything is okay in the morning, but if somebody takes it couple of bottles then the morning will be awful. Or let’s say – too much var will kill you?

Let’s see some nice scenarios how to use keyword var. I try also tell you what happens in my head when I see one or another example of these. So, using var we can write:

var messagingService = new MessagingService();

instead of:

MessagingService messagingService = new MessagingService();

Okay, it’s simple. I mean both cases. For longer class names var is like gift from heaven that makes our code readable again. But I can also survive first example, no proble. The information I need is there – the name of class, so I know what is the type of object I have to use.

Sometimes we don’t really care much about types. By example, we may need some automatic types in our code:

var stuff = new { X = 100, Y = 200 };

string[] words = { "chat", "stick", "many", "terror"
};

var
upperLowerWords =
   
from w in
words
   
select new { Substr = w.Substring(1), Upper = w.ToUpper() };

This code is clear (also in the mean that soon will some authorities contact me because of one of those strings). There are some autometic types and we can look at their definitions to find out what they have to offer.

Now let’s see how to confuse other developers who are reading our code.

var x = tmpObject.Search(criteria);

Why this is confusing? Well, to be honest, it is confusing because we gave a method fuzzy name. Giving properties and methods an informative names is deeper art than we first can expect. But this blog entry is not about naming stuff.

The point is that the example above hides some information that we may be interested in – what is the type of var? We have to go to Search() method and check out what it returns. Huh, very unconvenient, isn’t it?

Gunnar Peipman

Gunnar Peipman is ASP.NET, Azure and SharePoint fan, Estonian Microsoft user group leader, blogger, conference speaker, teacher, and tech maniac. Since 2008 he is Microsoft MVP specialized on ASP.NET.

    3 thoughts on “Using var keyword in C#

    • July 13, 2008 at 4:40 am
      Permalink

      Good observations. I have been loving using the “var” keyword, but I definitely agree that is is inappropriate in some places.

    • July 15, 2008 at 7:15 am
      Permalink

      Your IDE should tell you the type of x!

    • July 15, 2008 at 8:02 am
      Permalink

      Yes, Greg, it does. But when I’m reading the code I don’t want any avoidable problems to interrupt my mindwork.

    Leave a Reply

    Your email address will not be published. Required fields are marked *