Why would var be a bad thing?

前端 未结 17 1917
误落风尘
误落风尘 2020-12-04 17:21

I\'ve been chatting with my colleagues the other day and heard that their coding standard explicitly forbids them to use the var keyword in C#. They had no idea

17条回答
  •  旧巷少年郎
    2020-12-04 18:24

    In most cases when uses sensibly (i.e. a simple type initializer where the type and value are the same), then it is fine.

    There are some times when it is unclear that you've broken things by changing it - mainly, when the initialized type and the (original) variable type are not the same, because:

    • the variable was originally the base-class
    • the variable was originally an interface
    • the variable was originally another type with an implicit conversion operator

    In these cases, you can get into trouble with any type resolution - for example:

    • methods that have different overloads for the two competing types
    • extension methods that are defined differently for the two competing types
    • members that have been re-declared (hidden) on one of the types
    • generic type inference will work differently
    • operator resolution will work differently

    In such cases, you change the meaning of the code, and execute something different. This is then a bad thing.

    Examples:

    Implicit conversion:

    static void Main() {
        long x = 17;
        Foo(x);
        var y = 17;
        Foo(y); // boom
    }
    static void Foo(long value)
    { Console.WriteLine(value); }
    static void Foo(int value) {
    throw new NotImplementedException(); }
    

    Method hiding:

    static void Main() {
        Foo x = new Bar();
        x.Go();
        var y = new Bar();
        y.Go(); // boom
    }
    class Foo {
        public void Go() { Console.WriteLine("Hi"); }
    }
    class Bar : Foo {
        public new void Go() { throw new NotImplementedException(); }
    }
    

    etc

提交回复
热议问题