How to get a generic type from a generic definition and generic arguments?

In C #, how can I build a generic type from a generic definition and generic arguments like

var genericDefinition = typeof(List);
var genericArgument = typeof(string);
// How can I get the Type instance representing List<string> from the 2 variables above?

In my utility, the general argument is dynamically resolved. Is this possible in C #? Thanks in advance.

+4
source share
1 answer

There is no such thing as typeof(List). However, it typeof(List<>)works fine and is an open generic type. Then you just use:

var genericDefinition = typeof(List<>);
var genericArgument = typeof(string);
var concreteListType = genericDefinition.MakeGenericType(new[] {genericArgument});

and you must find what concreteListTypeis typeof(List<string>).

+4
source

Source: https://habr.com/ru/post/1648225/


All Articles