Skip to content

Instantly share code, notes, and snippets.

@thehoneymad
Last active August 20, 2016 00:02
Show Gist options
  • Save thehoneymad/7a7f20fa0b28e21fa8b5323ef9248b26 to your computer and use it in GitHub Desktop.
Save thehoneymad/7a7f20fa0b28e21fa8b5323ef9248b26 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mime;
using System.Text;
using System.Threading.Tasks;
namespace StackOverflow
{
public interface A { };
public interface B : A { };
public interface C : A { };
public interface D : B { };
public interface IMyInterface<in T> where T : A
{
};
public class FirstImpl<T> : IMyInterface<T> where T : B
{
};
public class SecondImpl<T> : IMyInterface<T> where T : C
{
};
class Program
{
public IMyInterface<T> Create<T>() where T : A, B, C
{
if (typeof(T) is B)
{
return new FirstImpl<T>();
}
if (typeof(T) is C)
{
return new SecondImpl<T>();
}
if(typeof(T) is D)
{
return new FirstImpl<T>();
}
return null;
}
static void Main(string[] args)
{
}
}
}
@snurkabill
Copy link

to be more specific (and I hope that formatting works in comments)

namespace StackOverflow
{
public interface A { };
public interface B : A { };
public interface C : A { };
public class D : B { };
public class E : C { };

public interface IMyInterface<in T> where T : A
{
};

public class FirstImpl<T> : IMyInterface<T> where T : B
{
};
public class SecondImpl<T> : IMyInterface<T> where T : C
{
};

class Program
{
    public IMyInterface<T> Create<T>() where T : A, B, C
    {
        if (typeof(T) is B)
        {
            return new FirstImpl<T>();
        }
        if (typeof(T) is C)
        {
            return new SecondImpl<T>();
        }
        return null;
    }

    static void Main(string[] args)
    {
          var correctImplementation = Create<D>();  // should be used FirstImpl
          var correctImplementation2 = Create<E>();  // should be used SecondImpl
    }
}

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment