Alex Rivera | Logout

What's the point of the var keyword?

Asked 2008-10-16T15:59:54.517
51

The var keyword does away with the need for an explicit type declaration and I have read with interest the SO discussion of when it might be appropriate.

I have also read about (but not used) Boo which seems to take things a step further by making it optional to declare a local variable. With Boo, both the type and the declaration can be implied.

Which leads me to wonder, why did the C# language designers bother to include a var keyword at all?

Update: Yes, var supports Anonymous types, but anonymous types by themselves do not necessitate the var keyword...

var anon = new { Name = "Terry", Age = 34 };

versus

anon = new { Name = "Terry", Age = 34 };
Edit
Report

1 Answer

6

This is a bit subjective, but I think designing C# 3.0 to have the "var" keyword for implicitly typed variables instead of no keyword makes the code more readable. For example, the first code block below is more readable than the second:

Obvious where the variable is declared:

var myVariable = SomeCodeToSetVariableHere;
myVariable = SomeOtherCodeTOSetVariable;

Not obvious where the variable is declared:

myVariable = SomeCodeToSetVariableHere;
myVariable = SomeOtherCodeTOSetVariable;

These are over-simplistic examples. I think you can see where this goes. In complex situations it might be nice to be able to find the place where a variable is actually defined.

answered 2008-10-16T16:06:34.660

Your Answer