Should I *always* favour implictly typed local variables in C# 3.0?

后端 未结 12 496
梦如初夏
梦如初夏 2020-12-09 15:48

Resharper certainly thinks so, and out of the box it will nag you to convert

Dooberry dooberry = new Dooberry();

to

var doo         


        
12条回答
  •  醉梦人生
    2020-12-09 16:23

    There's a really good MSDN article on this topic an it outlines some cases where you can't use var:

    The following restrictions apply to implicitly-typed variable declarations:

    • var can only be used when a local variable is declared and initialized in the same statement; the variable cannot be initialized to null, or to a method group or an anonymous function.
    • var cannot be used on fields at class scope.
    • Variables declared by using var cannot be used in the initialization expression. In other words, this expression is legal: int i = (i = 20); but this expression produces a compile-time error: var i = (i = 20);
    • Multiple implicitly-typed variables cannot be initialized in the same statement.
    • If a type named var is in scope, then the var keyword will resolve to that type name and will not be treated as part of an implicitly typed local variable declaration.

    I would recommend checking it out to understand the full implications of using var in your code.

提交回复
热议问题