TechQuiz: When to var

2012-06-17

  1. What does var mean in C#?
  2. Write a console application that outputs var when running the following line:

Console.WriteLine(var.GetType().Name);

  1. Why and how is this possible?

Answer

In the C# reference var is called a Conceptual Keyword. This means that it is used in combination with other code to give specific meaning to it.

In such a way, var behaves different then, for example, int.

The following code is not valid:


public class int {}

static  void Main()
{
    int var = new  int();

    Console.WriteLine(var.GetType().Name);
}

But this is valid:


public class var {}

static  void Main()
{
    var var = new  var();
    Console.WriteLine(var.GetType().Name);
}

Even though this is possible, it is of course something you don’t want to use because it will make your code very confusing.

When do you use var

var is used for ‘implicitly typed local variables’. When you use var, the compiler looks at your code and determines the type for you. The type is determined at compile time and cannot be changed after that.

So this is not allowed:

var myValue = new  List<string\>();
myValue = 3; // Error because int and List<string> are not compatible

But a situation where using var makes your code mo more readable is something like this:

Dictionary<Guid, List<Person>> myDictionary1 = new  Dictionary<Guid, List<Person>>();

or

var myDictionary1 = new  Dictionary<Guid, List<Person>>();

And in some situations, the use of var is required.

var myAnonymousType = new { Id = 1, Name = "I'm anonymous" };

Console.WriteLine(myAnonymousType.GetType().Name);

This will output something like: <>f__AnonymousType0`2

The compiler has created an anonymous type and created a name for it that won’t generate any conflicts with your existing code. Because this type is not known during development, the use of var is required.

When not to us var

Sometimes using var is not really useful or it makes your code harder to read.

var myValue = 3;
var myOtherValue = GetFoo();

In the first case, you could just say that the type of var will be an int. It makes no sense to let the compiler figure out the type for you.

In the second case, it’s not clear from reading the code what the type of myOtherValue will be. You have to inspect the GetFoo() function and check it’s return type to do this. Explicitly stating the type in your code will make it more readable.

So var is definitely a handy keyword in C#, to make your code nicer or even because it’s required but it is important that we apply it wisely.