If you are using C# 3.0 you may have come across the keyword
var. If not you can find information about it
here.
Basically the
var keyword allows you to declare any local variable as type
var and the compiler determines the type.
For example:
string myString = "Hello World";
is the same as:
var myString = "Hello World";
(Looks like
JavaScript!)
But when should we use
var?
The problem is readability; the more
var types you have the less readable it becomes for other to read your code. Sometimes it is also difficult to see what type your variable is; take for example:
var myObject = onotherObject.GetAValue(id);
Any idea what
myObject is?
So, as a convention I have started to use
var only when it is explicitly obvious what type it is:
var myString = "Hello World";
var myInt = 3;
var myButton = new Button();
and when it is an anonymous type:
1 var personQuery = from person in poeple
2 where person.Name == "RODJ"
3 select new { person.Name, person.Email };
4
5 foreach (var item in personQuery)
6 {
7 //Do something with every item.
8 }
and avoid:
var obj = DataFactory.CreateQueryWithSingleCriterion("Id", args.Value).Execute();
Hope that gives you some idea on when (or not) to use the
var type keyword.