Jakub Fojtik
Jakub Fojtik

Reputation: 706

Solving The type arguments for method cannot be inferred from the usage

I get this error: The type arguments for method 'ConsoleApplication1.Program.takeList<T>(System.ComponentModel.BindingList<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

I believe the compiler cannot guess the return type of the chooseList method, but it has to pass it to takeList method. Is there a way to make this work, but not decouple the chooseList method into the Main function??

class Program
{
    static BindingList<int> listOfInts;
    static BindingList<string> listOfStrings;
    //more lists

    static void takeList<T>(BindingList<T> list)
    {
        //do something
        return;
    }

    static object chooseList() //instead of object i would put BindingList<T>
    {
        int someCondition = 0;

        //code that changes someCondition so compiler doesnt know its value

        switch (someCondition)
        {
            case 1: return listOfInts;

            //more cases for more lists

            default: return listOfStrings;
        }
    }

    static void Main(string[] args)
    {
        Program testClass = new Program();
        var chosenList = chooseList();
        takeList(chosenList);
    }
}

EDIT:

Here is an opposite situation which should work. I would like to convert it to the above:

class Program
{
    static BindingList<int> listOfInts;
    static BindingList<string> listOfStrings;
    //more lists

    static void takeList<T>(BindingList<T> list)
    {
        //do something
        return;
    }

    static void Main(string[] args)
    {
        Program testClass = new Program();

        int someCondition = 0;

        //code that changes someCondition so compiler doesnt know its value

        switch (someCondition)
        {
            case 1:
                takeList(listOfInts);
                break;

            //more cases for more lists

            default:
                takeList(listOfStrings);
                break;
        }

        //Instead of the switch here, i would like to write takelist(doTheSwitch(someCondition));
    }
}

Upvotes: 0

Views: 1251

Answers (1)

supercat
supercat

Reputation: 81307

What you need is to have BindingList<T> derive from a non-generic abstract type or interface BindingList or IBindingList. You then need a TakeList() overload which can accept something of that non-generic type. Note that the generic form should probably shadow some of the methods in the abstract interface so that e.g. Add(object) would be shadowed by Add(T); other methods could be overloaded, so that both Contains(object) and Contains(T) would both be usable [the former would allow one to check whether a List<Cat> contains an Animal; even though Animal does not derive from Cat, a variable of type Animal could hold a reference to an instance of SiameseCat, which does].

Upvotes: 1

Related Questions