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

后端 未结 12 497
梦如初夏
梦如初夏 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 15:59

    I'm seeing a pattern for stackoverflow success: dig up old CodingHorror posts and (Jeopardy style) phrase them in terms of a question.

    I plead innocent! But you're right, this seemed to be a relatively popular little question.

    0 讨论(0)
  • 2020-12-09 16:00

    I use it only when it's clearly obvious what var is.

    clear to me:

    XmlNodeList itemList = rssNode.SelectNodes("item");
    var rssItems = new RssItem[itemList.Count];
    

    not clear to me:

    var itemList = rssNode.SelectNodes("item");
    var rssItems = new RssItem[itemList.Count];
    
    0 讨论(0)
  • 2020-12-09 16:00

    It only make sense, when you don't know the type in advance.

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

    No not always but I would go as far as to say a lot of the time. Type declarations aren't much more useful than hungarian notation ever was. You still have the same problem that types are subject to change and as much as refactoring tools are helpful for that it's not ideal compared to not having to change where a type is specified except in a single place, which follows the Don't Repeat Yourself principle.

    Any single line statement where a type's name can be specified for both a variable and its value should definitely use var, especially when it's a long Generic< OtherGeneric< T,U,V>, Dictionary< X, Y>>>

    0 讨论(0)
  • 2020-12-09 16:06

    It's of course a matter of style, but I agree with Dare: C# 3.0 Implicit Type Declarations: To var or not to var?. I think using var instead of an explicit type makes your code less readable.In the following code:

    var result = GetUserID();
    

    What is result? An int, a string, a GUID? Yes, it matters, and no, I shouldn't have to dig through the code to know. It's especially annoying in code samples.

    Jeff wrote a post on this, saying he favors var. But that guy's crazy!

    I'm seeing a pattern for stackoverflow success: dig up old CodingHorror posts and (Jeopardy style) phrase them in terms of a question.

    0 讨论(0)
  • 2020-12-09 16:07

    One of the advantages of a tool like ReSharper is that you can write the code however you like and have it reformat to something more maintainable afterwards. I have R# set to always reformat such that the actual type in use is visible, however, when writing code I nearly always type 'var'.

    Good tools let you have the best of both worlds.

    John.

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