Friday, October 17, 2008

What is Type Inference?

You might ask, "Lennie, in your previous blog about how bad variants are... what is type inference? Isn't it also a variant...?." The answer is yes and no, type inference comes from dynamic languages (remember Ruby, Python? yes those ladies!) and was added to the C# 3.0
language as part of the "var" keyword.

Basically what it does is that when you declare a variable with the "var" keyword its determined that the type of the variable from the data you assign to it, e.g.:

var firstName = "Lennie De Villiers"; // Hello, I'm a String type!
var age = 12; // yebo, I'm an int type!

but with type inference you can't change the type of the variable after its been assigned, e.g:

var firstName = 12; // Ooops, invalid!

With raw variants you can change the type of a variable all the time, like in the previous blog entry the MyNumber variable is a true variant since it is passed in as a number (probably a double) and then changed into a String type.

Microsoft added the "var" keyword since with LINQ queries the type of a variable is unknown but only know after execution.

Be careful of type inference since they're also bad and only should be used with LINQ queries when you execute them but afterwards (very important!) convert them to a proper known type else since you've the same problem where a developer looking at your code can't determine
the type of a variable - same problem with raw / true variants.

So to recap, type inference:
  • Infer the type from the value assigned to it;
  • Can't change the type after first assignment (its forever a string, int etc)
  • Bad coding practice since you still don't know the type of the variable.
True variants:
  • Bad coding practice since you still don't know the type of the variable.
  • Can change their type all the time, first a String then an int, then your PoolBoy class etc.
My golden run:
  • Type inference only when executing LINQ queries but afterwards convert to a proper type.
  • No variants, they're just bad!

No comments: