Class name as string in collection definition in C #

I have a class name as a string that I got with TYPE

Type type = myvar.GetType();  
string _className = type.ToString(); // getting the class name

My question is how to use this _className line here in the code below?

var data = this.ItemsSource as ObservableCollection<**_className**>()[2];

Here ItemsSource is shared.

Thanks in advance.

0
source share
1 answer

You can do this with reflection and Activator.CreateInstance:

Type type = myvar.GetType();  
string className = type.ToString(); 
Type genericType = Type.GetType(className);
Type observableCollectionType = typeof(ObservableCollection<>);
Type constructedType = observableCollectionType.MakeGenericType(genericType);
var constructedInstance = Activator.CreateInstance(constructedType);
+2
source

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