Mohsen
Mohsen

Reputation: 4266

Pass a list of types as Generic parameter

I was wondering if I could pass a List of types as generic parameter. I have a class which needs to get indefinite number of types and work with them. something like this:

class o<TTypeCollection>
{
    private void someMethod()
    {

        repository.Save < TTypeCollection.First() > (MyCollectionViewSource.CurrentItem as TTypeCollection.First());

    }
}

Upvotes: 3

Views: 928

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727047

There is no way to do template meta-programming in C# the C++ style, but you can do it using reflection:

private void someMethod() {
    var genericSave = repository // This can be done during initialization
        .GetType()
        .GetMethods()
        .Where(m => m.Name == "Save" && m.IsGenericMethodDefinition);
    var t = MyCollectionViewSource.CurrentItem.GetType();
    genericSave
        .MakeGenericMethod(new[] {t})
        .Invoke(new object[] {MyCollectionViewSource.CurrentItem});
}

Upvotes: 2

Related Questions