Why would var be a bad thing?

前端 未结 17 1898
误落风尘
误落风尘 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:08

    Here are the results of a test I ran on efficiency of var versus explicit typing:

      private void btnVar_Click(object sender, EventArgs e)
        {
            Stopwatch obj = new Stopwatch();
            obj.Start();
            var test = "Test";
            test.GetType();
            obj.Stop();
            lblResults.Text = obj.Elapsed.ToString();
        }
    
        private void btnString_Click(object sender, EventArgs e)
        {
            Stopwatch obj = new Stopwatch();
            obj.Start();
            string test = "Test";
            obj.Stop();
            lblResults.Text = obj.Elapsed.ToString();
    
        }
    

    First Label result is: 00:00:00 000034

    Second Label result is: 00:00:00 00008

    0 讨论(0)
  • 2020-12-04 18:11

    This is really a readability issue with your code.

    My personal preference is to only ever use "var" for anonymous types (indeed, if you wish to use anonymous types at all, you'll need to use var), and these mostly come from LINQ queries. In these cases, you have no choice but to use var if your query is projecting into a new (implicit & anonymous) type.

    However, C# 3.0 will happily let you use var anywhere you like, outside of LINQ and anonymous types, for example:

    var myint = 0;
    var mystring = "";
    

    is perfectly valid, and myint and mystring will be strongly-typed by the inferred values used to initialize them. (thus, myint is a System.Int32 and mystring is a System.String). Of course, it's fairly obvious when looking at the values used to initialize the variables what types they will be implicitly typed to, however, I think it's even better for code readability if the above were written as:

    int myint = 0;
    string mystring = "";
    

    since you can see immediately at a glance exactly which type those variables are.

    Consider this somewhat confusing scenario:

    var aaa = 0;
    double bbb = 0;
    

    Perfectly valid code (if a little unconventional) but in the above, I know that bbb is a double, despite the initializing value appearing to be an int, but aaa will definitely not be a double, but rather an int.

    0 讨论(0)
  • 2020-12-04 18:13

    Implicit typing is great, and people who flat-out prohibit it damage productivity and invite brittle code.

    It's almost like type-safe, compiler-checked duck typing, which is incredibly useful when refactoring. For example, if I have a method which returns a List, and I refactor it to return IEnumerable, then any callers to that method which have used the var keyword and only use IEnumerable methods will be fine. If I've explicitly specified, e.g., List, then I've got to go and change that to IEnumerable everywhere.

    Obviously, if any of the implicit-typing callers require List methods, then I'll get compile errors when I build, but if that's the case I probably shouldn't have been changing the return type anyway.

    0 讨论(0)
  • 2020-12-04 18:15
    var q = GetQValue();
    

    is indeed a bad thing. However,

    var persistenceManager = ServiceLocator.Resolve<IPersistenceManager>();
    

    is perfectly fine to me.

    The bottomline is: use descriptive identifier names and you'll get along just fine.

    As a sidenote: I wonder how do they deal with anonymous types when not allowed to use var keyword. Or they don't use them altogether?

    0 讨论(0)
  • 2020-12-04 18:16

    Forbidding it entirely means forbidding the use of anonymous types (which become incredibly useful as you use LINQ more).

    This is stupidity plain and simple unless someone can formalise a good reason to never use anonymous types.

    0 讨论(0)
  • 2020-12-04 18:18

    Understanding 'var' in Plain English

    I'm going to show you that using AND not using 'var' is about communicating clearly.

    I'm going to show examples of cases where using 'var' makes the code easier to read, and other examples when using var makes things hard to understand.

    More than that you'll see that how clear 'var' is depends a lot on what you name everything else in your code.

    Take this example:

    Jake said hello to Bill. He didn't like him so he turned and went the other way.

    Who went the other way? Jake or Bill? In this case "Jake" and "Bill" are like the type name. And "He" and "him" are like the var keyword. In this case it might help to be more specific. The following for example is much clearer.

    Jake said hello to Bill. Jake didn't like Bill so he turned and went the other way.

    In this case being more specific made the sentence clearer. But that's not always going to be case. In some cases being specific makes it harder to read.

    Bill likes books, so Bill went to the library and Bill took out a book that Bill has always liked.

    In this case it would be easier to read the sentence if we used "he" and in some cases left out his name all together, this is the equivalent of using the var keyword.

    Bill likes books, so he went to the library and took out a book that he has always liked.

    Those analogies cover the gist, but they don't tell the whole story. See in those examples there was only one way to refer to the person. Either with their name, for example Bill, or by a more general way, like "he" and "him". But we're only working with one word.

    In the case of the code you have two "words", the type and the variable name.

    Person p = GetPerson();
    

    The question now becomes is there enough information there for you to easily determine what p is? Would you still know what people is in this scenario:

    var p = GetPerson();
    

    How about this one:

    var p = Get();
    

    How about this one:

    var person = Get();
    

    Or this one:

    var t = GetPerson();
    

    Or this one:

    var u = Person.Get();
    

    Whether the keyword var works in a given scenario depends a lot on the context of the code, like what the names of the variables, classes, and methods are, as well as the complexity of the code.

    Personally I like to use the var keyword it's more comprehensive to me. But I also tend to name my variables after the type so I'm not really losing any information.

    That said sometimes I make exceptions, such is the nature of anything complex, and software is nothing if not complicated.

    0 讨论(0)
提交回复
热议问题