tags:

views:

113

answers:

4

Consider

public class Tuple<T1, T2>
{
    public Tuple(T1 v1, T2 v2)
    {
        V1 = v1;
        V2 = v2;
    }

    public T1 V1 { get; set; }
    public T2 V2 { get; set; }
}

public static class Tuple
{
    // MAGIC!!
    public static Tuple<T1, T2> New<T1, T2>(T1 v1, T2 v2)
    {
        return new Tuple<T1, T2>(v1, v2);
    }
}

Why does the part labeled "MAGIC" in the above work? It allows syntax like Tuple.New(1, "2") instead of new Tuple<int, string>(1, "2"), but ... how and why?

Why do I not need Tuple.New<int,string>(1, "2") ??

+3  A: 

This is "Type Inference". See a great article here for details.

Jeremy McGee
+4  A: 

This is called generic type inference and it works for generic methods only. You can pass instances of whatever types you want as the arguments to New and the compiler infers that you mean to return the particular generic Tuple that matches the arguments like Tuple<int, string>...

Jason Punyon
A: 

What is magic about it? You have two types, one that accepts generic type parameters and one that does not. They share the same name but they are not the same type. Try renaming one of them and see if it makes a little more sense to you.

/Klaus

klausbyskov
A: 

C# Compiler automatically infer type and compile your

Tuple.New(1, "2")

to

Tuple.New<int,string>(1, "2")
Guillaume