user2023861
user2023861

Reputation: 8208

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?

Upvotes: 0

Views: 335

Answers (3)

Eric Lippert
Eric Lippert

Reputation: 660563

The accepted answer is correct. For more background information, here are some resources for you:

A video of me explaining how type inference changed in C# 3.0:

http://ericlippert.com/2006/11/17/a-face-made-for-email-part-three/

How do we know that the type inference process will not go into an infinite loop?

http://ericlippert.com/2012/10/02/how-do-we-ensure-that-method-type-inference-terminates/

Why are constraints not considered during type inference? Read the comments in particular.

http://blogs.msdn.com/b/ericlippert/archive/2009/12/10/constraints-are-not-part-of-the-signature.aspx

Upvotes: 3

John Koerner
John Koerner

Reputation: 38087

The compiler can infer the type from the argument you passed in..

From the docs:

The compiler can infer the type parameters based on the method arguments you pass in; it cannot infer the type parameters only from a constraint or return value

Eric Lippert also has an interesting read on overload selection with generics: http://blogs.msdn.com/b/ericlippert/archive/2009/12/10/constraints-are-not-part-of-the-signature.aspx

Upvotes: 7

Jeroen Vannevel
Jeroen Vannevel

Reputation: 44438

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

Upvotes: 9

Related Questions