4

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)

Yochai Timmer
  • 48,127
  • 24
  • 147
  • 185

6 Answers6

29

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”.

Community
  • 1
  • 1
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • Is it bad practise to use `var` for everything? Why would you use `var` over explicit type casting? – Tom Gullen Jun 08 '11 at 16:05
  • 3
    @Tom We have multiple threads about this. The usage is highly controversial but I don’t really understand the problem. I use it almost everywhere, unless (very rarely!) when readability would suffer from it. – Konrad Rudolph Jun 08 '11 at 16:06
  • @Tom: You would explicitly specify the type when doing so makes the code clearer. Also, in a few rare cases, the compiler cannot infer the type, so you must specify it. – Robert Harvey Jun 08 '11 at 16:06
  • I know that, I meant "when declaring the variables type", wouldn't it be considered bad pracitce ? – Yochai Timmer Jun 08 '11 at 16:07
  • @Yochai: Why would it? It's a matter of coding style. In most cases the type is either obvious, or of not much interest to the person reading your code. `MyType type = new MyType();` Why say it twice? – Robert Harvey Jun 08 '11 at 16:08
  • @Robert Harvey: That's trivial, but what about: `SomeType hello = SomeWeirdMethodSomeOtherCompanyWrote()` ... Just as a matter of maintainability, when reviewing the code in the future, the type here is important – Yochai Timmer Jun 08 '11 at 16:18
  • 3
    @Yochai: So write it that way. In that context, it's clearer if you specify the type. But I get wiggy when people start using the term "bad practice." It implies that there is only "one right way" to do things, and there seldom is. – Robert Harvey Jun 08 '11 at 16:24
  • @Yochai What Robert said. But additionally: are you actually sure that the type is important? Because usually it isn’t (Eric Lippert goes into more detail here). If it were, then using interfaces would be a major design issue, and yet the best practice is to use interfaces instead of concrete types pretty much everywhere. – Konrad Rudolph Jun 08 '11 at 16:27
  • @Konrad Rudolph: Again, types are not important if you know what you're doing. Scripting languages work great too, without type declarations. But the benefit of using type names is for maintainability... Sure you know what you're doing, but will another programmer 2 months from now, look at the code and still understand it ? The type says a lot in these cases. – Yochai Timmer Jun 08 '11 at 16:33
  • @Yochai: Well said. When the type is not obvious from the context, specify it explicitly, if doing so improves readability. Otherwise, using `var` is just fine. – Robert Harvey Jun 08 '11 at 16:36
9

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.

Justin Morgan - On strike
  • 30,035
  • 12
  • 80
  • 104
5

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.

CodesInChaos
  • 106,488
  • 23
  • 218
  • 262
4

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.

vcsjones
  • 138,677
  • 31
  • 291
  • 286
2

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.

Platinum Azure
  • 45,269
  • 12
  • 110
  • 134
  • I never doubted the compiler, I just wandered if it's a good programming practice – Yochai Timmer Jun 08 '11 at 16:06
  • I would say it is only a *really* good practice if the type is basically understood, but really long to type out. (It really helps in using LINQ to Objects, for example.) – Platinum Azure Jun 08 '11 at 16:13
1

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.

mdm
  • 12,480
  • 5
  • 34
  • 53