1

in a method i have an object like this:

Activator.CreateInstance(Type.GetType(TargetObject))

and i need to pass this object to the other class that accept generic type:

public class Repository<T> where T : class
{
}

how can i use this object as T to Repository class?

adrakadabra
  • 11
  • 1
  • 2
  • just edited your question with the markup-tool –  Sep 21 '10 at 10:16
  • duplicate of http://stackoverflow.com/questions/266115/pass-an-instantiated-system-type-as-a-type-parameter-for-a-generic-class – sloth Sep 21 '10 at 10:20

2 Answers2

1

You can do that with reflection, for example:

Type repoType  = typeof(Repository<>).MakeGenericType(yourType);

but reflection soon begats more reflection - as you'd then need to talk about repoType via reflection. There are ways of minimising this impact, though:

  • non-generic interfaces (the simplest approach)
  • calling a generic method once via reflection that does all the additional work via regular static generic code

For the first, I might have an IRepository interface (non-generic), then it is just:

IRepository repo = (IRepository)Activator.CreateInstance(repoType);
repo.SomeNonGenericMethods(args); // etc
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
0

That's not possible. You have define T at design time.

gsharp
  • 27,557
  • 22
  • 88
  • 134
  • Sorry, but that is incorrect; you *can* define `T` at runtime (since .NET generics are provided by the runtime, not the compiler), but it isn't trivial and should be restricted only to necessary scenarios. – Marc Gravell Sep 21 '10 at 10:20
  • Agree with you. But he wanted to pass the created object to the class which is not possible. – gsharp Sep 21 '10 at 12:36