Can C# generics be this cool?

c#, generics, overloading

Solution

If you want type safety, the best you can do is probably:

class A<T1, T2>
{
    public void Call<T>(T1 arg1, T2 arg2) where T : IDoSomething<T1>, IDoSomething<T2>, new()
    {
        T b = new T();
        b.DoSomething(arg1);
        b.DoSomething(arg2);
    }
}

public interface IDoSomething<T>
{
    void DoSomething(T arg);
}

public class B : IDoSomething<int>, IDoSomething<float>
{
    void IDoSomething<int>.DoSomething(int arg)
    {
        Console.WriteLine("Got int {0}", arg);
    }

    void IDoSomething<float>.DoSomething(float arg)
    {
        Console.WriteLine("Got float {0}", arg);
    }
}

which you can use like:

var a = new A<int, float>();
a.Call<B>(1, 4.0f);

Problem

I want to be able to something like this: ``` class A<T1, T2> { public void Call(T1 arg1, T2 arg2) { B b = new B(); b.DoSomething(arg1); // determine which overload to use based on T1 b.DoSomething(arg2); // and T2 } } class B { public void DoSomething(int x) { // ... } public void DoSomething(float x) { // ... } } ``` I know it can be done with an if/else check, but that doesn't seem very elegant, especially when I have 20+ types to choose from.

Original source

Related problems