0

I would like to be able to pass the type into a generic method where I only know the name of the type.

I want to do something like the following, but I am getting an error.

var type = typeof(name);
var result = MyGenericMethod<type>();

Is this possible?

Currently I am doing a switch statement, but this is less than ideal as I need to update each time I need to add a new class.

switch (name)
{
    case "TypeName1":
        result = MyGenericMethod<TypeName1>();
        break;
    case "TypeName2":
        result = MyGenericMethod<TypeName2>();
        break;
    ...
}
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
user3284707
  • 3,033
  • 3
  • 35
  • 69

1 Answers1

-1

As far as I know, this part

var type = typeof(name);
var result = MyGenericMethod<type>();

is not possible.

Maybe if you can describe what you are trying to achieve, it is possible to find a solution for your problem though.

pieterVdM
  • 34
  • 5
  • Ok thank you for your comment, what I am trying to achieve is a short hand way to write the switch statement without having to have a separate case for each class, instead I can just pass in any class that is appropriate for the method and it will work, but by class name which is stored in a database table – user3284707 May 08 '19 at 20:50