Just look at this:
Collection<KeyValuePair<Predicate<T>, Action<T>>> x =
new Collection<KeyValuePair<Predicate<T>, Action<T>>>();
And now look at this:
var x = new Collection<KeyValuePair<Predicate<T>, Action<T>>>();
And, I dare, I double dare you, to tell me that there is no adventage in using the var
keyword.
Note: this is based on an actual declaration in some project I rather not mention.
Chances are that you think there is some drawback in using the var
keyword, well, there are, but they are all at compilation time. Your executable is as good as always. That's right var
isn't the same as object
, dynamic
, variant
, not at all! Instead it tells the compiler to declare the variable with the type of whatever you are assigning to it.
For example:
var x = 1;
x = "something"; //Error!!!
Ok, that may sound silly. "I know the type" - you say - "Why can't I just put it down?" - you ask - "Look, it is easy:"
int x = 1;
Well, three reasons:
- Sometimes you don't know the type, as Star mentions.
- Sometimes you just don't want to type the type (hint: look at the begining of this answer).
- Sometimes you want to have the flexibility to not need to tell the type.
This last point in particular comes in handy when creating Text Transformation Templates or Code Snippets, but also in you day to day copy paste.
Yet, just consider if you changed the return type of some arcane method... say you had:
List<string> MamboJambo()
{
//...
}
And now you have changed it to:
IList<string> MamboJambo()
{
//...
}
Oh, no! You have to update 50 classes now. Wait what? No, you don't! Because you have been following that recommendation that says to always use var
.
Note: Ok, not realistic example, still it gets the point across.