How do I check for a method exists in C # with a specific specific signature?

I want to check if a method is being implemented for certain parameters. In this case, I, for example, overload this method:

public class Transformations
{ 
    public string TransformFrom(string s) { return s;}
    public string TransformFrom(int i) { return "00" + i.ToString();}
    public string TransformFrom(DateTime dt) { return 
                       DateTime.ToString("MM/dd/yyyy HH:mm:ss.fff");}
}

      

Suppose I have a decimal value:

object obj = 1M;

      

If I call now TransformFrom(obj)

, I get an exception.

The other part of my program, unfortunately, only returns objects that are indeed concrete types, such as int or datetime. And I want to convert some of these objects to string so they can be logged. So this is a runtime issue. I also want my Transformations class to be generic enough for use in other programs, so any type of object can be.

Is there a quick way to find out that this overloading method doesn't exist?

+3


source to share


2 answers


In any case, you will get a compile-time error even if an overload occurred that took a decimal number. You can approach this in one of two ways depending on your needs:


To solve this problem at compile time, you need to specify the correct type.

object obj = 1;
var objAsInt = (int) obj;
var result = transformationInstance.TransformFrom(objAsInt);

      



If there is no proper overloading, you will get a compile-time error and you can work around this issue at design time.


To resolve this during use use reflection to find out if there is a type overload and if there is an instance of an instance.

object obj = 1;
var underlyingType = obj.GetType();
var method = typeof(Transformations).GetMethod("TransformFrom", new Type[] { underlyingType });
if(method != null)
{
    var result = method.Invoke(transformationInstance, new []{obj});
}

      

+2


source


It is possible to find out if there is any overload using reflection:

public static bool HasOverloadForArgument(Type targetType, string methodName, object arg)
{
    var methodInfo = targetType.GetMethod(name: methodName, types: new[] { arg.GetType() });
    return methodInfo != null;
}

      

Live example



I'm not sure what the whole idea is, as you won't be able to do much when the transform is not available at runtime.

Maybe your best bet dynamic

is to avoid unnecessary reflection and caching stuff like

var boxedInt = (object)1;
var boxedFloat = (object)1f;
dynamic dynamicInt = boxedInt;
dynamic dynamicFloat = boxedFloat;

var intResult = new Transformations().TransformFrom(dynamicInt); // works
var floatResult = new Transformations().TransformFrom(dynamicFloat); // throws binder exception

      

0


source







All Articles