YutingZuo
YutingZuo

Reputation: 15

How to conditionally create obj with constraints

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).

Upvotes: 1

Views: 54

Answers (1)

Support Ukraine
Support Ukraine

Reputation: 1026

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
    }
}

Upvotes: 1

Related Questions