Erick Velasco
Erick Velasco

Reputation: 124

Send T type to method with an object Instance

I'm sorry if I can't explain my question but it's hard for me.

I'm trying to send an T class to my method, but I don't have direct access to my object, so, I thought use the name for create an instance with reflections, but I don't know how to send the class T to my method.

This is th definition of my method

void RedirectToActivity<T>(bool closePrevious); 

And I have this code for call it

var activity = Activator.CreateInstance("myassembly", "MainActivity");
RedirectToActivity<????>(true);

With the first line I create an Instance of my class MainActivity.

In second line I need to send MainActivity class, and receive it like a T object in RedirectToActivity, but I don't know how to achieve this.

I need some like that...

RedirectToActivity<MainActivity>(true);

But I don't have direct access to MainActivity class.

I've tried this

RedirectToActivity<activity.GetType()>(true);
RedirectToActivity<typeof(activity)>(true);

But not works.

Upvotes: 0

Views: 34

Answers (1)

Nick Peppers
Nick Peppers

Reputation: 3251

Can you just add a generic parameter argument to your RedirectToActivity method?

void RedirectToActivity<T>(T activity, bool closePrevious)
{
    // Do Stuff here
}

And then pass your activity instance in:

var activity = Activator.CreateInstance<MainActivity>();
RedirectToActivity(activity, true);

Upvotes: 1

Related Questions