I've got separate implementations of a generic interface (one for classes, one for structs) and I wish to use a static Create method which handles construction. But I can't figure out how to make the compiler trust me about the correct type constraint. I totally get why it isn't working, but how do I get around this?
public interface ISomething<T> { }
internal class SomethingForReferenceTypes<T>
: ISomething<T> where T : class { }
internal class SomethingForValueTypes<T>
: ISomething<T> where T : struct { }
public static class Something
{
public static ISomething<T> Create<T>()
{
bool TIsAReferenceType = IKnowHowToFigureThisOut();
if (TIsAReferenceType)
return new SomethingForReferenceTypes<T>(); // ← T is not accepted here.
else
return new SomethingForValueTypes<T>(); // ← T is not accepted here.
}
}
I don't think you're going to be able to do this directly, but you could easily use reflection to create the instance:
Type openType = TIsAReferenceType
? typeof(SomethingForReferenceTypes<>)
: typeof(SomethingForValueTypes<>);
Type constructedType = openType.MakeGenericType(typeof(T));
object ret = Activator.CreateInstance(constructedType );
return (ISomething<T>) ret;
See more on this question at Stackoverflow