-2

I have the following SourceCode:

Type classType = x;
Type genericType = y;
var var1 = 1;
var var2 = 2;

object obj = Activator.CreateInstance(classType<genericType>);
obj.MyMethod(var1, var2);

Of course that didn't work. I have to use a Class in my <> and not an object of Type. And my other problem is, I can't call MyMethod without casting. But I have both Types at runtime, so there should be a method.

Edit: Sorry for the short question, I hoped it would be enough. But probably that would help to understand my problem:

class Base<T> where T : Entity
{
        public T[] MyMethod(int a)
        {
            return ActiveRecordMediator<T>.Find(a);
        }
}

class ABase : Entity
{
}

class BBase : Entity
{
}

public class AClass : Base<ABase>
{
}

public class BClass : Base<BBase>
{
}

Now I want to call myMethod. But I probably have something like this:

AClass<ABase> object = new AClass<ABase>();
object.MyMethod(10);

But I now that just at the runtime with my Type classType and my Type genericType. I can cast something like this: ((Base)object).MyMethod(10); But I need the generic Type here.

wydy
  • 71
  • 12
  • It's not clear what you are actually trying to do. That seems to be a problem that can be solved by a different approach. – Tim Schmelter Mar 16 '15 at 08:48
  • If you're having trouble with creating an instance of a generic class, [this answer](http://stackoverflow.com/a/266282/996081) may be of interest to you. – cbr Mar 16 '15 at 08:49
  • https://msdn.microsoft.com/en-us/library/b8ytshk6.aspx – Selman Genç Mar 16 '15 at 08:57

1 Answers1

0

You have to use MakeGenericType

dynamic obj = Activator.CreateInstance(classType.MakeGenericType(genericType));

obj.MyMethod(var1, var2);

and with dynamic calling MyMethod is easy (and if you have to call a single method a single time, it isn't even too much slow)

xanatos
  • 109,618
  • 12
  • 197
  • 280