Type inference != Dynamic typing

Local variable type inferencing is a new feature in C# 3.5 – a very “handy” one, in that it saves a lot of typing. Basically, it lets you do 

var dict = new Dictionary<string, List<int, Dictionary<int, string>>>();

instead of 

Dictionary<string, List<int, Dictionary<int, string>>> dict = Dictionary<string, List<int, Dictionary<int, string>>>();

That’s pretty cool, but remember, C# is still a statically typed language. dict is statically bound to the type Dictionary<string, List<int, Dictionary<int, string>>> and you cannot change it. You cannot do

dict = Dictionary<int, string>();

in the same method. The compiler will complain that the type on the RHS is not convertible to the statically bound type of dict.

Contrast this to a dynamically typed language like Javascript, which also uses the var keyword to declare variables. 

var x = 1;

x = new Array();

x = "23";

Or to Python 

x = 42

x = def fn(z) : return z + 1

In such languages, variables (x, in our example) simply act as placeholders and get bound to the type of the value they are holding at the moment. In the first example, x is holding an integer after executing the first line. After executing the second line, it’s holding an array. If the same two lines of code were to be written in a statically typed language, the second line would be correct only if an array is somehow convertible to an int.

The point of the post – don’t be misled by the var keyword. The variable it declares is still a good old statically typed variable.

One thought on “Type inference != Dynamic typing”

  1. C++ proposes to use the keyword “auto” for this reason, to indicate that the type is inferred, not that the variable is typeless.

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>