2

I have a generic method SampleMethod(param1, param2) and I need to call the method based on the config value. For example:

SampleMethod<long>(param1, param2);
SampleMethod<Guid>(param1, param2);

On the method call, type should change on the config value. I need to get the value from config file like app.config file.

public static Type RangeType
{
    get
    {
        Type rangeType;
        string rangeDataTypeString = ConfigurationManager.AppSettings["ShardRangeType"];

        switch (rangeDataTypeString.ToUpper())
        {
            case "LONG":
                rangeType = typeof (long);
                break;

            case "GUID":
                rangeType = typeof (Guid);
                break;

            default:
                rangeType = typeof (long);
                break;
        }

        return rangeType;
    }
}

When I try to call this based the configuration value and pass in this value to the above method like:

Type rangeType = Configuration.RangeType;
SampleMethod<rangeType>(param1, param2);

The rangeType in the above statement does not recognize as type, could someone suggest how to accomplish this. Thanks in advance!

SteelBird82
  • 759
  • 3
  • 10
  • 23
  • `it's not working` won't help much to give answer to your question. Can you please tell us what error are you getting exactly? – Sachin May 30 '16 at 06:12
  • Well you'd at least need to `cast` your parameters. If those are standard data types you can use [`Convert.ChangeType`](https://msdn.microsoft.com/en-us/library/system.convert.changetype%28v=vs.110%29.aspx) – Manfred Radlwimmer May 30 '16 at 06:15
  • My bad, not working I meant, rangeType is not recognized in the statement: SampleMethod(param1, param2); – SteelBird82 May 30 '16 at 06:19
  • you can use List if it will match in your criteria – Darshan Faldu May 30 '16 at 06:20
  • Seems to me like you are trying to solve the problem with the wrong Design. Can you give an example of `SampleMethod`? Even if you were able to pass Type like you want, wouldnt you want `SampleMethod` be different based on the actual type? – Itsik May 30 '16 at 06:22

2 Answers2

1

If "SampleMethod" method exist in same class that you want Invoke it:

this.GetType().GetGenericMethod("SampleMethod",rangeType).Invoke(null,param1, param2);
Reza ArabQaeni
  • 4,848
  • 27
  • 46
1

Type arguments to invocations of generic methods are compiled. You can't put a variable into them. If you want to pass a Type as a parameter to the method, add it as a parameter to the method.

If you know that you have a very limited set of type arguments, you can create a set of conditional invocations (eg. with switch).

Otherwise you can use reflection to construct the appropriate generic method and invoke it (as shown in Reza's answer).

Without knowing exactly what you are doing with SampleMethod suggesting other alternatives about how to do it is impossible.

moreON
  • 1,977
  • 17
  • 19