What Does "Var" Mean in C#

What does var mean in C#?

It means that the type of the local being declared will be inferred by the compiler based upon its first assignment:

// This statement:
var foo = "bar";
// Is equivalent to this statement:
string foo = "bar";

Notably, var does not define a variable to be of a dynamic type. So this is NOT legal:

var foo = "bar";
foo = 1; // Compiler error, the foo variable holds strings, not ints

var has only two uses:

  1. It requires less typing to declare variables, especially when declaring a variable as a nested generic type.
  2. It must be used when storing a reference to an object of an anonymous type, because the type name cannot be known in advance: var foo = new { Bar = "bar" };

You cannot use var as the type of anything but locals. So you cannot use the keyword var to declare field/property/parameter/return types.

Use of var keyword in C#

I still think var can make code more readable in some cases. If I have a Customer class with an Orders property, and I want to assign that to a variable, I will just do this:

var orders = cust.Orders;

I don't care if Customer.Orders is IEnumerable<Order>, ObservableCollection<Order> or BindingList<Order> - all I want is to keep that list in memory to iterate over it or get its count or something later on.

Contrast the above declaration with:

ObservableCollection<Order> orders = cust.Orders;

To me, the type name is just noise. And if I go back and decide to change the type of the Customer.Orders down the track (say from ObservableCollection<Order> to IList<Order>) then I need to change that declaration too - something I wouldn't have to do if I'd used var in the first place.

What's the point of the var keyword?

Update: There are two related questions here, actually:
1. Why do I have to declare variables at all?
2. What use is "var" in a language that makes you declare variables?

The answers to (1) are numerous, and can be found elsewhere for this question. My answer to (2) is below:

As other commenters have said, LINQ uses this for its anonymous types. However, LINQ is actually an instance of a more general problem where the type of the right-hand side of an expression is either unknown to the programmer, or is extremely verbose. Consider:

SomeGeneric<VeryLongTypename<NestedTypename>> thing = new   
SomeGeneric<VeryLongTypename<NestedTypename>>();

Verbose and error-prone, right? So now they let you do this:

var thing = new SomeGeneric<VeryLongTypename<NestedTypename>>();

By reducing the duplication of information, errors are eliminated. Note that there aren't just typing errors, here: it's possible for the type of the left-hand expression to be mistyped in such a way that the compiler can silently cast from left to right, but the cast actually loses some property of the rvalue. This is even more important when the types returned by the rvalue may be unknown or anonymous.

var: a Type or a keyword

var is a contextual keyword - along with yield, add and get for example.

In other words, you can use it as an identifer without prefixing it with @, but it still has a special meaning to the compiler in some places (i.e. where a type name is expected for a local variable declaration).

Using var to declare a local variable asks the compiler to infer the type of the variable based on the expression on the right hand side. For example:

var list = new List<string>();
var anon = new { Foo = "bar" };

The type of list is List<string>; the type of anon is an anonymous type, also introduced in C# 3. Part of the reason for introducing var in C# 3 was to allow for strongly typed variables using anonymous types - the variable still has the appropriate compile-time type, even though you couldn't explicitly state that type.

There are a few cases where var doesn't work, however, if the compiler doesn't have enough information:

var cantUseNull = null;
var cantUseLambda = x => x.Length;

There are others too. In each case you could just cast the expression on the right-hand side, so that the compiler knew what to use - but in that case you might as well just declare the variable explicitly instead.

<plug>
You can read more about this in C# in Depth. Fortunately, the chapter covering this is still available for free from the first edition page (you want chapter 8). I can't remember how much I've changed this chapter in the second edition...

</plug>

What is the equivalent of the C# 'var' keyword in Java?

There is none. Alas, you have to type out the full type name.

Edit: 7 years after being posted, type inference for local variables (with var) was added in Java 10.

Edit: 6 years after being posted, to collect some of the comments from below:

  • The reason C# has the var keyword is because it's possible to have Types that have no name in .NET. Eg:

    var myData = new { a = 1, b = "2" };

    In this case, it would be impossible to give a proper type to myData. 6 years ago, this was impossible in Java (all Types had names, even if they were extremely verbose and unweildy). I do not know if this has changed in the mean time.

  • var is not the same as dynamic. variables are still 100% statically typed. This will not compile:

    var myString = "foo";
    myString = 3;
  • var is also useful when the type is obvious from context. For example:

    var currentUser = User.GetCurrent();

    I can say that in any code that I am responsible for, currentUser has a User or derived class in it. Obviously, if your implementation of User.GetCurrent return an int, then maybe this is a detriment to you.

  • This has nothing to do with var, but if you have weird inheritance hierarchies where you shadow methods with other methods (eg new public void DoAThing()), don't forget that non-virtual methods are affected by the Type they are cast as.

    I can't imagine a real world scenario where this is indicative of good design, but this may not work as you expect:

    class Foo {
    public void Non() {}
    public virtual void Virt() {}
    }

    class Bar : Foo {
    public new void Non() {}
    public override void Virt() {}
    }

    class Baz {
    public static Foo GetFoo() {
    return new Bar();
    }
    }

    var foo = Baz.GetFoo();
    foo.Non(); // <- Foo.Non, not Bar.Non
    foo.Virt(); // <- Bar.Virt

    var bar = (Bar)foo;
    bar.Non(); // <- Bar.Non, not Foo.Non
    bar.Virt(); // <- Still Bar.Virt

    As indicated, virtual methods are not affected by this.

  • No, there is no non-clumsy way to initialize a var without an actual variable.

    var foo1 = "bar";        //good
    var foo2; //bad, what type?
    var foo3 = null; //bad, null doesn't have a type
    var foo4 = default(var); //what?
    var foo5 = (object)null; //legal, but go home, you're drunk

    In this case, just do it the old fashioned way:

    object foo6;

Why would var be a bad thing?

The writers of the .Net Framework Design Guidelines (awesome book) that came out in November 2008 recommend considering using var when the Type is obvious and unambiguous.

On the other hand, if using var would result in an ambiguity when reading the code, as Anton Gogolev pointed out, then it's better not to use it.

in the book (Annex A), they actually give this example:

var names = new List<string>(); // good usage of var

string source = GetSource();
var tokens = source.Split(' '); // ok; most developers know String.Split

var id = GetId(); // Probably not good; it's not clear what the type of id is

It's possible that, to ensure that readability is not subjected to the whims of lowly developers, your organisation has decided that you were not worthy of var and banned it.

It's a shame though, it's like having a nice tool at your disposal but keeping it in a locked glass cabinet.

In most cases, using var for simple types actually helps readability and we must not forget that there is also no performance penalty for using var.

Use of var type in variable declaration

How about this...

double GetTheNumber()
{
// get the important number from somewhere
}

And then elsewhere...

var theNumber = GetTheNumber();
DoSomethingImportant(theNumber / 5);

And then, at some point in the future, somebody notices that GetTheNumber only ever returns whole numbers so refactors it to return int rather than double.

Bang! No compiler errors and you start seeing unexpected results, because what was previously floating-point arithmetic has now become integer arithmetic without anybody noticing.

Having said that, this sort of thing should be caught by your unit tests etc, but it's still a potential gotcha.

What to use: var or object name type?

Beyond the obvious use of var with LINQ, I also use it to abbreviate hairy variable declarations for readability, e.g.:

var d = new Dictionary<string, Dictionary<string, Queue<SomeClass>>>();

In general, I get a kind of comfort (for want of a better word) from static typing that makes me reluctant to give it up. I like the feeling that I know what I'm doing when I'm declaring a variable. Declaring a variable isn't just telling the compiler something, it's telling the person reading your code something.

Let me give you an example. Suppose I have a method that returns a List<string>. This code is certainly correct, and I think it's how 90% of C# developers would probably write it:

List<string> list = MyMethod();

Obviously, right? In fact, here's a place you could just as easily use var.

True enough. But this version of the code isn't just declaring a variable, it's telling me what the person who wrote it is intending to do:

IEnumerable<string> list = MyMethod();

The developer who wrote that code is telling me "I'm not going to be changing this list, nor am I going to use an index to access its members. All I'm going to do is iterate across it." That's a lot of information to get across in a single line of code. It's something you give up if you use var.

Of course, you're not giving it up if you weren't using it in the first place. If you're the kind of developer who would write that line of code, you already know that you wouldn't use var there.

Edit:

I just reread Jon Skeet's post, and this quote from Eric Lippert jumped out at me:

Implicitly typed locals are just one small way in which you can deemphasize the how and thereby emphasize the what.

I think that actually in a lot of cases using implicit typing is leaving the what implicit. It's just OK to not dwell on the what. For instance, I'll casually write a LINQ query like:

var rows = from DataRow r in parentRow.GetChildRows(myRelation)
where r.Field<bool>("Flag")
orderby r.Field<int>("SortKey")
select r;

When I read that code, one of the things I think when I'm reading it is "rows is an IEnumerable<DataRow>." Because I know that what LINQ queries return is IEnumerable<T>, and I can see the type of the object being selected right there.

That's a case where the what hasn't been made explicit. It's been left for me to infer.

Now, in about 90% of the cases where I use LINQ, this doesn't matter one tiny little bit. Because 90% of the time, the next line of code is:

foreach (DataRow r in rows)

But it's not hard to envision code in which it would be very useful to declare rows as IEnumerable<DataRow> - code where a lot of different kinds of objects were being queried, it wasn't feasible to put the query declaration next to the iteration, and it would be useful to be able inspect rows with IntelliSense. And that's a what thing, not a how thing.



Related Topics



Leave a reply



Submit