LA.NET [EN]

Mar 19

Today, we’ll keep looking at generics and we’ll see how type inference is used to simplify the code we need to write to invoke a method. Lets start with a simple example:

public class Test
{
    public void DoSomething<T>( T item )
    {
        Console.WriteLine(item + " is of type " + typeof(T));
    }
}
And yes, you can also define generics at the method level…Now, without type inference, we would have to specify the type of the generic type arguments expected by the method:

var t = new Test();
t.DoSomething<Int32>(10);

The good news is that the MS team added generic type arguments inference. In practice, this means that we can simply call the method *without* explicitly specifying its type arguments:

t.DoSomething(10);

Now, there’s one important detail which might get you by surprise…Take a look at the following snippet:

Object number = 10;
var t = new Test();
t.DoSomething(number);

What will appear in the console now? If you’re thinking that the type will be System.Int32 like in the previous snippet, you’re wrong. You see, the compiler uses the variable’s data type (instead of the actual type of the object referred by that variable) when it has to infer the generic argument type. Another interesting aspect of using generics with methods is trying to understand how thing works with overloads. What should happen when the compiler finds these method overloads:

public class Test
{
    public void DoSomething<T>( T item )
    {
        Console.WriteLine("generic");
    }
    public void DoSomething(String item)
    {
        Console.WriteLine("non generic");
    }
}

Yes, it does compile…but how does the compiler find the correct method for each of the following calls:

var t = new Test();
t.DoSomething(10); //generic
t.DoSomething("10");//non-generic
t.DoSomething<String>("10");//generic

As you can see, the compiler will always choose a more specific call over a generic match (and that’s why the first method ends up being invoked for the first call). Notice also that when you explicitly specify the generic type argument, then the compiler is obliged to call the generic method.

And I guess that’s all for now. Stay tuned for more.

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>