C# 'var' keyword versus explicitly defined variables

This question already has an answer here:

  • Use of var keyword in C# 86 answers

  • So, is there some sort of performance gain to be had from changing the List to a var

    No but this is not the only valid reason for a refactoring. More importantly, it removes redundance and makes the code shorter without any loss in clarity.

    I've always been taught that explicitly defining a variable, rather than using a dynamic, is more optimal.

    You misunderstand what var means. This is not in any way dynamic, since it produces the same output. It just means that the compiler figures the type for the variable out by itself. It's obviously capable of doing so, since this is the same mechanism used to test for type safety and correctness.

    It also removes a completely useless code duplication. For simple types, this might not be much. But consider:

    SomeNamespace.AndSomeVeryLongTypeName foo = new SomeNamespace.AndSomeVeryLongTypeName();
    

    Clearly, in this case doubling the name is not just unnecessary but actually harmful.


    Nope. They emit the exact same IL.

    It's just a matter of style.

    var has the benefit that makes it easier for you to change the return type of functions without altering other parts of source code. For example change the return type from IEnumerable<T> to List<T> . However, it might make it easier to introduce bugs.


    The var keyword does not actually declare a variable with a dynamic type. The variable is still statically typed, it just infers the type from the context.

    Its a nice shortcut when you have a long typename (generic typenames can be long)

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

    上一篇: C#var关键字使用情况

    下一篇: C#'var'关键字与显式定义的变量