Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using different generic types on a method's argument and return type

Tags:

c#

generics

I am working on a generic utility method that takes a generic argument and returns a generic type--I hope that makes sense!--but I want the return type to be a different type from the argument.

Here's what I'm thinking this should look like if I mock it up in pseudo code:

public static IEnumerable<R> DoSomethingAwesome<T>(T thing) 
{
    var results = new List<R>();

    for (int xx = 0; xx < 5; xx++)
    {
        results.Add(thing.ToRType(xx));
    }

    return results;
}

With generics not being able to infer the return type how would I go about doing something like this? So far, my Google-Fu has failed me.

like image 739
amber Avatar asked Dec 13 '22 12:12

amber


1 Answers

// You need this to constrain T in your method and call ToRType()
public interface IConvertableToTReturn
{
    object ToRType(int someInt);
}

public static IEnumerable<TReturn> DoSomethingAwesome<T, TReturn>(T thing)
    where T : IConvertableToTReturn
{
    Enumerable.Range(0, 5).Select(xx => thing.ToRType(xx));
}
like image 197
Justin Niessner Avatar answered May 15 '23 10:05

Justin Niessner