0

I have this code snippet that I want to simplify:

        switch (typeString)
        {
            case "boolean":
                CreateSimpleRows<bool>(ref group, value);
                break;
            case "datetime":
                CreateSimpleRows<DateTime>(ref group, value);
                break;
            case "double":
                CreateSimpleRows<double>(ref group, value);
                break;
            case "int32":
                CreateSimpleRows<int>(ref group, value);
                break;
            case "int64":
                CreateSimpleRows<long>(ref group, value);
                break;
            case "string":
                CreateSimpleRows<string>(ref group, value);
                break;
        }

The method is declared as CreateSimpleRows<T>. I tried passing a System.Type instance, but that didn't work.

I came across this answer to a similar question: Pass An Instantiated System.Type as a Type Parameter for a Generic Class

I've checked and I've seen that there's a MakeGenericMethod in the MethodInfo class. Thing is, I don't know how to convert "CreateSimpleRows" into a MethodInfo instance.

Is what I'm thinking of achieving even possible? Thanks in advance for the replies.

Community
  • 1
  • 1
raistdejesus
  • 109
  • 1
  • 11
  • Of course this is cool, if your goal is to "simplify" I would stay away from reflection. –  Oct 06 '10 at 08:33
  • @jdv yeah, it just hit me now that using Reflection defeats my intent to simplify. Thanks for pointing that out. – raistdejesus Oct 06 '10 at 08:48
  • possible duplicate of [How to use reflection to call generic Method?](http://stackoverflow.com/questions/232535/how-to-use-reflection-to-call-generic-method) – nawfal Jan 18 '14 at 07:45

1 Answers1

3

To get a MethodInfo, you call Type.GetMethod:

MethodInfo method = typeof(TypeContainingMethod).GetMethod("CreateSimpleRows");
MethodInfo generic = method.MakeGenericMethod(typeArgument);

Note that if you want to get a non-public method you'll need to use the overload of GetMethod which takes a BindingFlags as well.

It's not really clear why you want to do this with reflection though. While your current snippet is repetitive, it's at least simple to understand. Using reflection is likely to make things more error-prone, and you'd still have to map typeString to a Type to start with.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • I see. I guess in my initial intent was to remove the repetitive portions of the code. Seeing your answer to the similar question gave me hope that it was possible. It's only occurred to me now that using Reflection actually defeats my original intent.Thanks for the quick reply! :) – raistdejesus Oct 06 '10 at 08:47