When to use var and when to use Strongly types?

This question already has an answer here:

  • Use of var keyword in C# 86 answers

  • The var keyword is compiler feature which allows implicit type declarations - I would opt to use var purely because it's shorter.

    People will probably say you lose readability using var , however, what makes

    MyClass myobj = new MyClass()
    

    any more readable than

    var myobj = new MyClass()
    

    The only scenario where I do think it does make sense to use an explicit type is when declaring an interfaced type ie

    IMyInterface myobj = new MyClass()
    

    Or casting

    MyBaseClass myObj = new MyClass()
    

    Then again, you could argue those cases as well because the same code would be functionality equivalent

    var myObj = (IMyInterface)new MyClass()
    var myObj = (MyBaseClass)new MyClass()
    

    In general, I very rarely see the need to explicitly define the type as it's inferred by the instantiated type.


    Both are equivalent, in fact if you write #1 the compiler will resolve it to #2. What matters then is thee readability.

    There is a long debate on why var should be avoided just because it has a negative impact on readability. My opinion is that it should be avoided when possible, however in extreme cases writing an explicit type for an expression could be just too cumbersome (just write a complicated linq expression with groupping or double groupping and try to write down its type).


    There is no difference except for readability.

    I'd pick Approach 1 because I consider it more readable.

    链接地址: http://www.djcxy.com/p/53816.html

    上一篇: 在C#中声明变量

    下一篇: 何时使用var和什么时候使用强类型?