5 Years
Discussion Span
Last Post by Narue

Let's start with the conceptually simpler one. var is something of a placeholder that says "deduce the type for me". Since the compiler already knows the type on the right hand side of an initialization, why should you be forced to specify it explicitly on the left hand side? Prior to the introduction of var , we had to do stuff like this:

Dictionary<string, MyClass> foo = new Dictionary<string, MyClass>();

Pretty redundant, no? With var , you can simply tell the compiler to deduce the type and only say it once:

var foo = new Dictionary<string, MyClass>();

The two definitions above are functionally identical. In both cases the type is statically defined as Dictionary<string, MyClass> . Now, this would be useful, but perhaps not so useful as to justify a new keyword. Another benefit of var is that it deduces types that you don't know, such as anonymous types (which are used heavily in LINQ):

var foo = new { a = "test", b = 123 };

dynamic is what everyone feared var was upon hearing about it. While var doesn't circumvent static type checking, dynamic does; dynamic is C#'s way of moving type checks from compile time to runtime. The intention is to simplify tasks such as interfacing COM, which has been notoriously tedious prior.

This article has been dead for over six months. Start a new discussion instead.
Be sure to adhere to our posting rules.