Complete code

The following code is from a book of Tod Golding (wrox)

public void InferParams<I, J>(I val1, J val2){...}

public void InferParams<I, J>(int val1, string val2) {...}

InferParams<int, string>(14, "Test");// call the second function
InferParams(93, "Param2"); // call the first function

Can anybody explain the difference Why there is no compile error Thanks!





Answer this question

Complete code

  • Oanimao

    The compiler can infer the generic types in the case of the first function because the types are used as arguments. It cannot do this in the second function because I and J are not used in the parameters. This is an educated guess on my part, but when it sees the first call to InferParams, it sees that the types I and J are explicitly specified, so it calls the method where the types I and J could not have been inferred. In the second case, the types for I and J are not specified, and so they must be inferred. So, it has no choice but to call the first method, since it can't infer the arguments for the second InferParams method.


  • Peter Gissel

    using System;
    using System.Collections.Generic;
    using System.Text;

    namespace ConsoleApplication1
    {
    public class Program
    {
    public static void Main(string[] args)
    {
    A a = new A();
    Console.WriteLine(a.InferParams<int, string>(0, ""));
    Console.WriteLine(a.InferParams(0, ""));
    Console.ReadLine();
    }
    }

    public class A
    {
    public A()
    {
    }

    public string InferParams<I, J>(I val1, J val2)
    {
    return "123";
    }

    public string InferParams<I, J>(int val1, string val2)
    {
    return "321";
    }
    }
    }

    Output:

    321

    123



  • Complete code