Will using 'var' affect performance?

后端 未结 12 1650
南方客
南方客 2020-11-22 14:01

Earlier I asked a question about why I see so many examples use the varkeyword and got the answer that while it is only necessary for anonymous types, that it is used noneth

12条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-22 14:41

    "var" is one of those things that people either love or hate (like regions). Though, unlike regions, var is absolutely necessary when creating anonymous classes.

    To me, var makes sense when you are newing up an object directly like:

    var dict = new Dictionary();
    

    That being said, you can easily just do:

    Dictionary dict = new and intellisense will fill in the rest for you here.

    If you only want to work with a specific interface, then you can't use var unless the method you are calling returns the interface directly.

    Resharper seems to be on the side of using "var" all over, which may push more people to do it that way. But I kind of agree that it is harder to read if you are calling a method and it isn't obvious what is being returned by the name.

    var itself doesn't slow things down any, but there is one caveat to this that not to many people think about. If you do var result = SomeMethod(); then the code after that is expecting some sort of result back where you'd call various methods or properties or whatever. If SomeMethod() changed its definition to some other type but it still met the contract the other code was expecting, you just created a really nasty bug (if no unit/integration tests, of course).

提交回复
热议问题