Is the use of the keyword "var" considered harmful?

Possible duplicate:
Using the var keyword in C #

I use it almost all the time, unless I immediately assign this variable, in which case this is not an option. Good or bad?

+4
source share
3 answers

Used implicitly typed variables ( var keyword):

  • Great : if you need an anonymous type.
  • Good : when the type is obvious ( var sb = new stringbuilder(); )
  • Bad : when the type is not so obvious ( var doc = repo.getdocs("base"); )

If you find that you use it, if often, it is probably good. Using it all the time means that sometimes people have to research what type you use. A clear listing of what type is used should be clearly considered.

+3
source

You must strike a balance between ease of writing and ease of reading. Of course, you can hover over the next use of the variable to see the type deduced, but if you are not reading the code in the IDE, this can be a problem.

One edge case I came across recently was that I tried to manually replace individual instances of Foo in my project with instances of Bar (improved Foo ). I would do "Find All" for Foo , and it turns out I missed a few because I did var quux = GetSomething() , where GetSomething returns an instance of Foo . But, this is a bit of an extreme case, and I would not attach too much weight to this alone regarding the use of var .

0
source

This is apparently the recommended method (if you use a tool such as Resharper, it defaults to replacing the specific type with "var" where possible). I personally prefer to use certain types for readability. However, if the code is of good quality and the methods are of normal length, it remains readable even when using "var". A long discussion is discussed here: Using the var keyword in C #

Otherwise, the efficiency of using var does not affect performance (this is not like using an "object" and type casting).

0
source

Source: https://habr.com/ru/post/1308304/


All Articles