1

I have 2 class which has a different constraint, and I want to create obj for them conditionally in a generic function. Example below.

public class Foo1<T>
 where T : class, Interface1, new()
{
   // do sth...
}

public class Foo2<T>
 where T : class, Interface2, new()
{
   //do sth...
}

public static void Create<T>()
{
    if(typeof(Interface1).IsAssignableFrom(typeof(T))
   {
       var obj = new Foo1();
       //...
   } else if (typeof(Interface2).IsAssignableFrom(typeof(T))
   {
       var obj = new Foo1();
       //...
   }
}

And I got the error "There is no implicit reference conversion from T to Interface1/2". The problem is similar to Similiar to How to conditionally invoke a generic method with constraints?, but I can find a place to add (dynamic).

Fred
  • 3,365
  • 4
  • 36
  • 57
YutingZuo
  • 15
  • 3

1 Answers1

1

You can create an instance of a generic class using reflection.

public static void Create<T>()
{
   if (typeof(Interface1).IsAssignableFrom(typeof(T)))
   {
        var d1 = typeof(Foo1<>);
        Type[] typeArgs = { typeof(T) };
        var makeme = d1.MakeGenericType(typeArgs);
        object o = Activator.CreateInstance(makeme);
    }
    else if (typeof(Interface2).IsAssignableFrom(typeof(T))
    {

        // same for Foo2
    }
}
Fred
  • 3,365
  • 4
  • 36
  • 57
Support Ukraine
  • 978
  • 6
  • 20