.NET generic class instance - passing a variable data type

Posted by FerretallicA on Stack Overflow See other posts from Stack Overflow or by FerretallicA
Published on 2010-06-02T00:52:05Z Indexed on 2010/06/02 1:23 UTC
Read the original article Hit count: 275

As the title suggests, I'm tyring to pass a variable data type to a template class. Something like this:

frmExample = New LookupForm(Of Models.MyClass) 'Works fine

Dim SelectedType As Type = InstanceOfMyClass.GetType() 'Works fine
frmExample = New LookupForm(Of SelectedType) 'Ba-bow!
frmExample = New LookupForm(Of InstanceOfMyClass.GetType()) 'Ba-bow!

LookupForm<Models.MyClass> frmExample;
Type SelectedType = InstanceOfMyClass.GetType();
frmExample = new LookupForm<SelectedType.GetType()>(); //Ba-bow
frmExample = new LookupForm<(Type)SelectedType>(); //Ba-bow

I'm assuming it's something to do with the template being processed at compile time but even if I'm off the mark there, it wouldn't solve my problem anyway. I can't find any relevant information on using Reflection to instance template classes either.

(How) can I create an instance of a dynamically typed repository at runtime?

© Stack Overflow or respective owner

Related posts about c#

Related posts about vb.net