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”.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With