Declare variable in C#
Possible Duplicate:
Use of var keyword in C#
Hi, I am pretty new in C#,
I would like to know the best practices in declaring variables.
I know it is possible to use VAR (explicit declaration) or the DataType when declaring a variable (implicit).
I would appreciate your opinions thanks
I always try to give my variable declarations useful names that describe what they are for, camel-cased, declared at the top of the class.
Most people will say that using var is for the best. It reduces the complexity of future maintainance, for example if you change the return type of a particular method, then you won't have to go and change the type of every variable that is assigned to from that method, because you have used var when declaring the variable.
This type of question has also been covered many times on stackoverflow already. See for example: Use of var keyword in C#
It's the other way around. This is an explicit type:
int x = 42;
This is an implicit type:
var x = 42;
You should use the implicit declaration when you have to (ie when you use anonymous types) or when the code gets more readable.
Example:
// anonymous type
var y = new { item: "asdf" };
// avoid repeating long type names
var z = new System.Text.StringBuilder();
Personally, I'm happy to use var myVariable = new ReferenceType();
because I know that I'm going to get a variable of the type and having to specify the type again is duplication. Sometimes you need to be specific when declaring ie: IComplexThing var = new ComplexThing();
For interating an array and collections, then the foreach (var item in items) is OK because again I know what type I will be getting.
I usually try to use a MyType result = from x in queryable where x=>x.Id == id select x;
since the type is known prior to the query, but for queries like var result = from x in queryable where x=>x.Id == id select new { Id, Name, Description};
the type is generated at query time and is not know. I try to stay away from that type of queries.
上一篇: 使用var运算符而不是类类型
下一篇: 在C#中声明变量