Variables and Standard Types

What is var?

The var keyword is a special keyword in C#. First introduced as part of the C# 3.0 language release it serves several purposes. It's primary purpose is a language feature called type inference. Now, to get to grips with what that actually means, let's look at an example:

using System; public class Program...

In our example above, we've declared to variables, one an int, the other a string. We know what both of those types are, because we have explicitly stated what they are. You can also use var:

using System; public class Program...

 

That is still perfectly valid C#, and the reason this works, is because the compiler will infer what type that one and two represent based on their assignments. In the first instance, the value 1 is the literal integer value, so the compiler determines that var one is an integer. In the second instance, it understands that "two" is a string literal, so it can infer that var two is a string.

This can help us when writing code in a couple of ways:

1 - We can use var to help minimise the amount of code we have to type, e.g.:

ConcurrentDictionary<string, int> dictionary = new ConcurrentDictionary<string, int>(); // Long hand
var dictionary = new ConcurrentDictionary<string, int>(); // Shorter

2 - Anonymous types (we'll come to these in a future tutorial) wouldn't be possible without the var keyword:

var person = new { Name = "John Smith" };

 

Page 13 of 17