M
M
Mikhail Mikhail2015-07-03 15:54:20
C++ / C#
Mikhail Mikhail, 2015-07-03 15:54:20

Is it better to auto or specify the exact type of a variable?

Good afternoon.
nevertheless, I got to the resolver and a small question arose, since he advises throughout the code to change the exact type indicated by me to auto.
what is he doing this for?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Ashur_451, 2015-07-03
@Ashur_451

It all depends on the context of the application.
one)

var list = new ObservableCollection<SomeReallyLongTypeName>();

Here, as it were, it is already clear what kind of type the list will have and there is not much point in explicitly talking about it.
Thus, we shorten the code and make it easier to read.
2)
ComplexType businessObject = DoSomeWork().OtherWork(a,b).GetResult(someArgs);

Here it is worth thinking about the obviousness of the returned type, sometimes it will be more convenient to leave the specific type after all.
Although if we use LINQ, it is still customary to use it with auto types.
PS Resharper is a cool thing, but it's not always worth it to follow everything he says. Read Martin's "Clean Code" or something like that, you will feel a little more confident in these subtleties.
PPS I'm terrible at writing, I know, sorry ;)

P
Pavel Osadchuk, 2015-07-03
@xakpc

it's a matter of code conventions.
I will give an example from c # (there is var instead of auto),
for example, if we have a simple type or a local variable is created where something of an unknown type is put

int i = 5; 
// или
double localF = _globalF;

If we create a collection or a class - and from the line of creation it is clear what kind of type, then I prefer var
var c = new MySuperLongClassName(); 
// или
var lm = new List<Model>();

D
DancingOnWater, 2015-07-03
@DancingOnWater

The brevity of the record. A classic use case is the use of iterators.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question