The title is kind of obscure. What I want to know is if this is possible:
string typeName = <read type name from somwhere>;
Type myType = Type.GetType(typeName);
MyGenericClass<myType> myGenericClass = new MyGenericClass<myType>();
Obviously, MyGenericClass is described as:
public class MyGenericClass<T>
Right now, the compiler complains that 'The type or namespace 'myType' could not be found." There has got to be a way to do this.
My requirements were slightly different, but will hopefully help someone. I needed to read type from a config and instantiate the generic type dynamically.
Finally, here is how you call it. Define the type with a backtick.
You can't do this without reflection. However, you can do it with reflection. Here's a complete example:
Note: if your generic class accepts multiple types, you must include the commas when you omit the type names, for example:
Some additional how to run with scissors code. Suppose you have a class similar to
Suppose at runtime you have a FooContent
If you were able to bind at compile time you would want
However you cannot do this at runtime. To do this at runtime you would do along the lines of:
To dynamically invoke
Markdown(IEnumerable<FooContent> contents)
Note the usage of
dynamic
in the method call. At runtimedynamicList
will beList<FooContent>
(additionally also beingIEnumerable<FooContent>
) since even usage of dynamic is still rooted to a strongly typed language the run time binder will select the appropriateMarkdown
method. If there is no exact type matches, it will look for an object parameter method and if neither match a runtime binder exception will be raised alerting that no method matches.The obvious draw back to this approach is a huge loss of type safety at compile time. Nevertheless code along these lines will let you operate in a very dynamic sense that at runtime is still fully typed as you expect it to be.
If you know what types will be passed you can do this without reflection. A switch statement would work. Obviously, this would only work in a limited number of cases, but it'll be much faster than reflection.
Unfortunately no there is not. Generic arguments must be resolvable at Compile time as either 1) a valid type or 2) another generic parameter. There is no way to create generic instances based on runtime values without the big hammer of using reflection.