I am trying to get rid of some references by using string representation of certain types. But compiler is not letting me do it the way I want in case of generic methods. I tried this:
IContainer container = components as IContainer;
Type type = Type.GetType("MyNamespace.MyType");
foreach (var component in container.Components.OfType<Type.GetType("MyNamespace.MyType")>()) {
...
}
And this:
foreach (var component in container.Components.OfType<type>()) {
...
}
For the first loop I get this: “Operator ‘<‘ cannot be applied to operands of type ‘method group’ and ‘System.Type’, and for the second the variable is out of scope for some reason. Why is this happening and is there a way around it? Thanks in advance.
You can use Type.MakeGenericType. Example:
Example for a List with a typeparameter determined from a string:
This gives you the same as
But you still can’t use a Type instance to call Enumerable.OfType. You could use something like this instead:
Of course, this get’s messy quickly, so I would consider changing your approach. Why do you wan’t to use strings?