Using var for implicitly typed variables in C#

I wanted to spend some time talking about the “var” keyword in C# because I’ve heard a number of misconceptions about it since it’s been introduced.

The var keyword is really just syntactic sugar that allows C# to resolve the type of a variable at compile time.  For example, the code

int i = 0;

is equivalent to

var i = 0;

The type of variable “i” has simply been inferred from it’s assignment.  The right side of the assignment is an integer, so the compiler treats i as an int throughout the rest of the scope of the variable.

var really shines when using anonymous types.  For example, I could write code like this.

var person = new { FirstName = "William", LastName = "Riker" };
var numbers = Enumerable.Range(0, 100).Select((i) => new { Number = i, Square = i*i });

Using var with anonymous types allows us to assign them to a variable without explicitly defining a type for the variable.  There still is a type for the variable, but it is a class that is implemented by the compiler.

One misconception is that the var keyword itself is a “type”.  Another is that it causes the compiler to not need to know the type of the variable.  Both of these are untrue, and using var like this does not remove statically typed nature of the language.  This is why whenever you use a “var” statement, you must include an assignment.

For example, doing this wouldn’t work as the compiler would throw an error because it doesn’t know what type “j” is supposed to be.

var j;
Advertisements

One comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s