0

I have class name as string that I got using TYPE

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

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

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

Here ItemsSource is generic.

Thanks in advance.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Hafiz H
  • 399
  • 5
  • 22
  • http://stackoverflow.com/questions/9842222/dynamic-cast-to-generic-type – Mitch Wheat Jun 02 '14 at 10:52
  • Instead of using the `string`, you can use the value of `type` along with some reflection to create an instance of a generic type. You can't use either of those directly in code though (that is, you can't write code of the form `ObservableCollection` where the `xxx` is a variable). – Dan Puzey Jun 02 '14 at 10:54
  • Could try with `Type.GetType(_className)` to fetch the type. – Jite Jun 02 '14 at 10:55
  • 1
    Try `var data = (this.ItemsSource as IList)[2]`. Then you don't need to know the type – amnezjak Jun 02 '14 at 10:59
  • I didn't try creating an instance of a generic type, I will do and let me check – Hafiz H Jun 02 '14 at 11:03
  • (this.ItemsSource as IList)[2] works, thanks all – Hafiz H Jun 02 '14 at 11:05

1 Answers1

3

You can do that using reflection and the Activator.CreateInstance method:

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);
Brian Watt
  • 225
  • 1
  • 7
Sheridan
  • 68,826
  • 24
  • 143
  • 183