adviner
adviner

Reputation: 3557

C# Generic T assign type Tuple

I have the following class:

public static class Support<T>
{
    public static T CreateKeyNameJSONTT(IEnumerable<Tuple<T, T>> a, Action<T> b)
    {
        T result = default(T);

        try
        {
            foreach (var entry in a)
            {
              b((T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromInvariantString("[ \"" + entry.Item1 + "\", " + entry.Item2 + "\" ]"));
            }
            result = (T)Convert.ChangeType(true, typeof(T));
        }
        catch
        {
            result = (T)Convert.ChangeType(false, typeof(T));
        }

        return result;
    }
}

I cant seem to call it correctly though:

var result = Support.CreateKeyNameJSONTT(List<Tuple<int, string>> list, (string entry) =>
{
});

The error i get is "Using the generic type List requires 1 argument"

Can anyone please help on this. Nothing I do is working so I may be mis-understanding something.

Upvotes: 0

Views: 1599

Answers (1)

Servy
Servy

Reputation: 203802

You won't be able to use a List<Tuple<int, string>> because in the definition of the method you've said that the first parameter is: IEnumerable<Tuple<T, T>>. The key point here is that the first and second generic arguments to Tuple are the same; they can't be different in what you pass it when calling the method.

You could call it this way though:

List<Tuple<string, string>> list = null;
var result = Support<string>.CreateKeyNameJSONTT(list , (string entry) =>
{
});

That will compile. (And fail at runtime, but that's another issue.)

Note that the generic argument needed to be supplied to Support in the form of: Support<string>. The type cannot be inferred for a class's generic argument, only (potentially) for methods. You could get type inference if you changed the definition to:

public static class Support
{
    public static T CreateKeyNameJSONTT<T>(...)

Upvotes: 3

Related Questions