When should I use "var" instead of "object"? [closed]
I was wondering when should you use var
?
Almost anything in C#, except for maybe the primitives and a few more odd cases, derive from Object.
So wouldn't it be a better practice to use that actual types ? or at least object
?
(I've been programming for a while, and my strict point of view is that var
is evil)
You misunderstand: var
isn’t a type. var
instructs the compiler to use the correct type for a variable, based on its initialisation.
Example:
var s = "hello"; // s is of type string
var i = 42; // i is of type int
var x = new [] { 43.3 }; // x is of type double[]
var y = new Foo(); // y is of type Foo
Your variables are still strongly typed when using var
.
As a consequence, var
isn’t “evil”. On the contrary, it’s very handy and as I’ve said elsewhere, I use it extensively. Eric Lippert, one of the main people behind C#, has also written in great detail about whether var
is bad practice. In a nutshell, “no”.
You're conflating var
with dynamic
, I think. Using var
is exactly the same* as if you had written out the entire type name, and the compiler renders them into the same code. Eric Lippert's blog offers some excellent information on what the var
keyword does and when to use it.
From Eric Lippert's article Uses and misuses of implicit typing:
Summing up, my advice is:
- Use var when you have to; when you are using anonymous types.
- Use var when the type of the declaration is obvious from the initializer, especially if it is an object creation. This eliminates redundancy.
- Consider using var if the code emphasizes the semantic "business purpose" of the variable and downplays the "mechanical" details of its storage.
- Use explicit types if doing so is necessary for the code to be correctly understood and maintained.
- Use descriptive variable names regardless of whether you use "var". Variable names should represent the semantics of the variable, not details of its storage; "decimalRate" is bad; "interestRate" is good.
*Some might take issue with my "exactly the same" statement. It isn't strictly true for anonymous types, but that's because you can't legally write out the type name.
Using object
you'd lose all static type information (and when used on a value type it even causes boxing). So using object
is very different from using var
.
var
on the other hand is equivalent to using the actual(static) type. So you use it when stating the actual type is either impossible or inconvenient.
One scenario where
var
is necessary is when using anonymous types. They have no name(nitpick: only a compiler generated name that you don't know), so you can't name the type explicitly.One case where using
var
is convenient is when you're typename is very long. This happens sometimes when using nested generics.And in
foreach
loops you avoid the unsafe implicit cast.
var
and object
are two entirely different things.
With var
, the compiler is inferring the type for you. An object
is an object, and you lose any information you had about the instance since C# is a strongly typed language.
See section 26.1 from the C# specification:
In an implicitly typed local variable declaration, the type of the local variable being declared is inferred from the expression used to initialize the variable. When a local variable declaration specifies var as the type and no type named var is in scope, the declaration is an implicitly typed local variable declaration.
Your "strict point of view" is a little misinformed... var
DOES use the actual type. The compiler analyzes the return type of the expression on the right hand side and uses that as the type of the assignment.
var
is not a type. var
says to the compiler 'I'm not sure/can't be bothered typing the proper type name here, please infer the type for me based on the context of this statement'.
Object
casts the object to type Object
. As a result you lose any type information, so can no longer call specific methods, access properties etc that are defined at a level lower in the hierarchy than Object
.
精彩评论