Search code examples
c#syntaxvar

When should I use "var" instead of "object"?


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)


Solution

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