LINQ: What is the purpose of var?

Sep 22, 2005 • 3 minutes to read

Larsenal, a C9’er posted a comment on the C9 forums about the Introducing LINQ video and asked a really good question so I thought I should repost my response here.

**Larsenal’s Question **“_I’ve watched this video on LINQ in C#. If the type is set at compile time, what’s the benefit of using the “var” keyword? It seems like it just makes the code less readable.

I look at the first example here, and wonder why not just replace the var with string[]?”_****

**My (slightly modified) Answer **If you’ve never heard of var, var is a new way to declare variables in C# 3.0 that uses implicit typing. Let’s show a quick couple of examples.

Before 3.0 string myString = “hello”; int myInt = 5; float myFloat = 5.5f;

After 3.0 var myString = “hello”; var myInt = 5; var myFloat = 5.5f;

The distinction here is that var is not the same as object, or the JavaScript “var” data type as it’s actually strongly typed, but inferred from whatever the value is being assigned.

**Create your own types with var **The big reason for var in my opinion is that LINQ enables you to create or “project” wholly new data types without having to create the type themselves. This is known as projection.

Let’s look at a sample query that I blogged about earlier:****

string[] aBunchOfWords = {“One”,“Two”, “Hello”, “World”, “Four”, “Five”};

var result = from s in aBunchOfWords where s.Length == 5 select s;

In this example, I am projecting the string “s”, so I could have easily replaced var with the type IEnumerable as shown in bold below and my code would have worked fine.

**IEnumerable**** **result = from s in aBunchOfWords where s.Length == 5 select s;

But what if I wanted to project something more complex, like a type that contains

  1. the string
  2. the length of the string as an integer
  3. the first three characters of the substring

Using the power of var, this is pretty easy as shown in bold below:

var result = from s in aBunchOfWords where s.Length == 5 //Creates a new anonymous type with name/value pairs select** new {Value=s, Length=s.Length, FirstThreeLetters=s.Substring(0,3)}**;

//Print values foreach (var x in result) Console.WriteLine(“Value: {0}, Length:{1}, SubString:{2}", x.Value, x.Length, x.FirstThreeLetters);

This prints: Value: Hello, Length:5, SubString:Hel Value: World, Length:5, SubString:Wor

As you can see, I can use “select new” and project my own custom type with field name/value pairs. Under the covers var infers the field names, field values, and field data types and creates an anonymous type with the three fields I projected.

Without var, you would have to create the anonymous type yourself, which basically means you have to create a custom class for the projected type as shown below:

public** class MyType**** ****{**** **public**** string Value;** **public**** int Length;** **public**** string FirstThreeLetters;** **}****

The subsequent code would work like shown below (using another new feature, object initializers):****

IEnumerable**** result = from s in aBunchOfWords where s.Length == 5 select** new MyType {Value=s, Length=s.Length, FirstThreeLetters=s.Substring(0,3)}**;

While I get the same results as in the previous example, you can see how var saves me the trouble of defining my own type. In the var example, the compiler is creating its own version of the “MyType” class, but you as a LINQ developer don’t need to worry about that, but If you really don’t like var, you can of course manually create your own class and map them to LINQ queries as I showed above and everything will still “just work”.

When you’re dealing with projection, var is awesome in that it really eliminates the grunt work of defining your own type, which, when you get to nested types can be pretty ugly :)

You can find a whole slew of projection operator samples at: http://msdn.microsoft.com/vcsharp/future/linqsamples/projection/default.aspx

LINQ

LINQ: Creating your first Extension Method

We want your LINQ Feedback!