Search code examples
c#generic-type-argument

Why am I not required to specify type arguments in C#?


I have a function that takes a generic type argument. It's pretty simple:

private static void Run<T>(IList<T> arg)
{
    foreach (var item in arg)
    {
        Console.WriteLine(item);
    }
}

I've found that I can call this function without specifying the type argument:

static void Main(string[] args)
{
    var list = new List<int> { 1, 2, 3, 4, 5 };

    //both of the following calls do the same thing
    Run(list);
    Run<int>(list);

    Console.ReadLine();
}

This compiles and runs just fine. Why does this work without specifying a type argument? How does the code know that T is an int? Is there a name for this?


Solution

  • Type inference.

    The same rules for type inference apply to static methods and instance methods. The compiler can infer the type parameters based on the method arguments you pass in

    http://msdn.microsoft.com/en-us/library/twcad0zb.aspx