12 January 2020

To var or not to var... in C-Sharp

Using the var keyword in C# to declare variables does save you some thought and can seem to speed things up, but as pointed out by Ian Griffiths in his books about programming in C#, "...although var saved you some work when you wrote the code, that gain is quickly wiped out by the additional thought required every time you go back and look at the code."

That said, there are some situations in which var is warranted. One is to avoid writing the name of the type twice.

So this:
    List<int> numbers = new List<int>();

Can be written as:
    var numbers = new List<int>();

You can drop the first List<int> without making this harder to read because the name is right there in the initializer.

C# supports anonymous types, and as the name suggests, it’s not possible to write the name of such a type. In these situations, you may be compelled to use var. (In fact, the var keyword was introduced to C# only when anonymous types were added.)

No comments: