-1

Hey I have tried to use a Type as Parameter and using typeof(Class) to get the type.

My problem is that i cant use the Type in a Task like this:

CreditorList = new ObservableCollection<DataModel>();

Is this possible??

Code for Reference:

private void Dg_Loaded(object sender, RoutedEventArgs e)
        {
            CreateList(typeof(CreditorClient));
        }    

async private void CreateList(Type DataModel)
        {
            CreditorList = new ObservableCollection<DataModel>();
        }

Error:

Cannot implicitly convert type '...OberservableCollection' to '...DataModel.CreditorClient'

  • 1
    What type is CreditorList ? – Titian Cernicova-Dragomir Sep 08 '17 at 11:51
  • Why not use `ObservableCollection`? – juanferrer Sep 08 '17 at 11:59
  • This is almost never the right thing to do. Even having created the object successfully, you will have trouble actually _using_ the object if you can't statically declare the generic type for variables which will be used to access the object. But, if you insist, this is an all-too-often posted question. One of the earliest duplicates is shown above. – Peter Duniho Sep 08 '17 at 20:49

3 Answers3

0

You can't do this directly you would have to use reflection to create the list it you want to pass it as a Type.

CreditorList = Activator.CreateInstance(typeof(ObservableCollection<>).MakeGenericType(DataModel))

I would recommend you find a design where this is not required though. Reflection is slow and ugly and you might run into problems with it.

Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357
0

Try to use reflection:

private void Dg_Loaded(object sender, RoutedEventArgs e)
{
    CreateList(typeof(CreditorClient));
}    

async private void CreateList(Type DataModel)
{
    Type genericType = typeof(ObservableCollection<>).MakeGenericType(DataModel);
    CreditorList = new ObservableCollection<Activator.CreateInstance(genericType)>();
}
koca2000
  • 67
  • 12
-1

Please try the following code:

private void Dg_Loaded(object sender, RoutedEventArgs e)
        {
            CreateList<CreditorClient>();
        }    

async private void CreateList<TModel>()
        {
            CreditorList = new ObservableCollection<TModel>();
        }
Max Zuber
  • 19
  • 5