S
S
skosterin882017-03-07 10:50:34
C++ / C#
skosterin88, 2017-03-07 10:50:34

Use var or declare type explicitly?

Recently installed Resharper. I noticed that he underlines the declarations of variables with a dotted line, where their type is specified explicitly and recommends using var instead. That is, he wants instead of

double d = 5.0;
MyObject myObj = new MyObject();

It was
var d = 5.0;
var myObj = new MyObject();

Personally, I have always believed that built-in types should be declared explicitly, i.e. a variable of type double must be declared through double. But instances of classes can be declared through var. But Resharper seems to think otherwise, and that confuses me.
What do you think is better?

Answer the question

In order to leave comments, you need to log in

5 answer(s)
K
kvasek, 2017-03-07
@kvasek

No difference.
A local variable with an implicit type is strongly typed as if the type were given explicitly, only the compiler determines the type.
https://msdn.microsoft.com/uk-ua/library/bb383973.aspx

D
Dmitry Kovalsky, 2017-03-07
@dmitryKovalskiy

No difference.
In my opinion, the description is
just shorter and prettier. There is no double mention of the type, which in this context is butter oil.

D
Dmitry Makarov, 2017-03-09
@DmitryITWorksMakarov

I write "var" wherever the compiler and algorithm allow (in the sense that sometimes when creating an object of a certain class through "new" or when returning an object from a method, it must be put into a variable of the parent class or interface type).
I am too lazy in this matter: I am too lazy to write the name of the type twice or even to understand what kind of type it is and how exactly it is written.
When creating variables of type double, I also use "var" and suffixes:
again, for reasons of laziness.
In addition, for reasons of general style, it is also nice to write "var" everywhere.

B
Boris the Animal, 2017-10-14
@Casper-SC

var can be written where it is clearly visible what type this variable has.
I don't want to create a long declaration where the name of the class is duplicated. You can immediately see what type is in the Linq variable. I think that it is unacceptable to shove var anywhere. Why would the reader of the code need to hover over the mouse to see what type of variable it is. Why write var instead of int . It's out of the way at all. In resharper, not all default rules should be considered the only true ones. They can be turned off.

D
d-stream, 2017-03-07
@d-stream

In my opinion, where the type is known, an explicit indication of the type will still be better.
My view actually grew out of the exploitation of both strongly typed languages ​​and completely untyped languages, where you could write somewhere in a rare branch
x="qqq"
and then somewhere zababahat loop
for(x=0, x=x+1, x <10)
and eventually catch a rare error in runtime -)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question