1

How can I replace <T> from the name of the class dynamically? I would like to be able to replace T using string of the class name.

I tried

Type type = Type.GetType(classname);
configuration.GetSection($"ProjectConfig").Get <type> ()

I get a syntax error for the second line in for type:

Type is a variable but used as a type

chiaDev
  • 389
  • 3
  • 17
  • You can work with generic classes and methods using Reflection, but you can't do what you are showing – Flydog57 Jul 28 '21 at 04:29
  • Could you describe what you are attempting to achieve here ? Dynamically instantiate a generic class ? you could do so using reflection – Anu Viswan Jul 28 '21 at 04:31
  • 2
    `.Get(type)` exists, but you should explain the context. Right now this sounds like an XY problem. – Jeremy Lakeman Jul 28 '21 at 04:34
  • added more explanation in the post. I am would like to replace T using string of the classname – chiaDev Jul 28 '21 at 04:43
  • What type is `configuration` variable? Why same section would contain different types? If configurations are JSON, you can retrieve configurations as a string and deserialize it to the type by type name – Fabio Jul 28 '21 at 05:04
  • 1
    Does this answer your question? [Pass An Instantiated System.Type as a Type Parameter for a Generic Class](https://stackoverflow.com/questions/266115/pass-an-instantiated-system-type-as-a-type-parameter-for-a-generic-class) – j-petty Jul 28 '21 at 05:08

1 Answers1

0

you cant do that.

.Net generics are not dynamic, they are resolved at compile time. E.g. supposed you use List<string> and List<int>, at compile time, the compiler will create 2 new classes List`string and List`int.

Generics are meant to provide strong typing at compile time.

If you're asking how to bind the content of configuration to your specific object, You can instantiate the object dynamically using reflection and then use configuration.Bind(anyObject) to populate it.

dna01
  • 33
  • 3
  • .Net generics *are* dynamic. `typeof(List<>)..MakeGenericType(type)` – Jeremy Lakeman Jul 28 '21 at 05:10
  • @JeremyLakeman - No, they are not. Your sample code is still compiled and strongly-typed. – Enigmativity Jul 28 '21 at 07:38
  • Types are loaded into memory dynamically by the runtime. `.MakeGenericType(type)` creates a new "instance" of a generic type in memory, with its own static variables. Want a more complex example? `AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes()).Select(t => typeof(List<>).MakeGenericType(t))` (with exception handling). None of those `List` appear anywhere in my source code, none were discovered by the compiler, yet they are all now types loaded into memory, which I can create instances of using reflection. – Jeremy Lakeman Jul 29 '21 at 00:50