Which is better to auto or to specify the exact type of a variable?

  • 0
    Good day.
    nevertheless, I got to the resolver and a small question arose, since he advises throughout the code to change the exact type that I specified to auto.
    why is he doing this?
    C++ Anonymous, Feb 16, 2019

  • 3 Answers
  • 0
    It all depends on the context of the application.


    1)
    var list = new ObservableCollection<SomeReallyLongTypeName>();


    Here, as it were, it’s clear what type of list will have and there’s no point in talking about it explicitly.

    This way we make the code shorter and easier to read.


    2)
    ComplexType businessObject = DoSomeWork().OtherWork(a,b).GetResult(someArgs);


    Here it is worth thinking about the obviousness of the return type, sometimes it will be more convenient to still leave a specific type.

    Although if we use LINQ it is still customary to use it with auto types.


    P.S. Resharper is cool, but you don't always have to be fooled by everything he says. Read Martin "Clean Code" or something like that, you will feel a little more confident in these subtleties.


    P.P.S I write awful, I know sorry;)
    Anonymous

  • 0
    this is a code conventions question.


    I will give an example from c # (there var instead of auto)

    for example, if we have a simple type or create a local variable where something of an unknown type is put
    int i = 5; 
    // или
    double localF = _globalF;


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

  • 0
    Brevity of the record. A classic use case is using iterators.
    Holden Waters

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!