Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use "var" instead of "object"? [closed]

Tags:

syntax

c#

var

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)

like image 800
Yochai Timmer Avatar asked Nov 27 '22 21:11

Yochai Timmer


1 Answers

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

like image 181
Konrad Rudolph Avatar answered Dec 07 '22 00:12

Konrad Rudolph