Is it possible to use an unrelated type as a parameter of a generic type in C #?

I have C # generic:

public class Generic<TParameter> { ... } 

It doesn't seem like I can use unrelated types as type parameters. I get error CS1031: Type expected when I try to do the following:

 var lGenericInstance = new Generic<List<>>(); 

How to use an unbound type as a typical type parameter? Are there any workarounds? My general class just uses reflection, so I can get the list of provided type members as strings.


Update . My question about an unbound type was answered, so I looked at a separate question that relates to my specific problem.

+7
source share
2 answers

Try the following:

 class Foo<T> { } class Bar<T> { } Type unboundBar = typeof(Bar<>); Type unboundFoo = typeof(Foo<>); Type boundFoo = unboundFoo.MakeGenericType(new[] { unboundBar }); Console.WriteLine(boundFoo.Name); Conosle.WriteLine(boundFoo.GetGenericArguments().First().Name); 

Please note that you cannot write

 Type boundFoo = typeof(Foo<Bar<>>) 

as the specification explicitly states:

An unrelated generic type can only be used in a typeof expression (ยง7.6.11).

( Bar<> is not used here as a parameter for typeof-expression; rather, it is a general type parameter for typeof-expression parameter.)

However, it is completely legal in the CLR, as shown above, using reflection.

But what are you trying to do? You cannot have instances of unrelated types, so I don't understand.

+5
source

the question you ask is, in my opinion, erroneously formulated.

the error you have in your code is that you cannot have List<> anywhere, as this requires a type.

this one: var lGenericInstance = new Generic<List<>>(); fails on List and not on Generic ... well on both because they are chained ... :)

so your question is more like:

Why can't I create an object of type List<> ? or why can't I list List<> as T for my general class?

+2
source

All Articles