C# check if there is an overload method with the specific type

505 views Asked by At

The title is maybe not that clear, I'll try to explain on an example:

I'm replacing the AutoMapper with a custom DTO mapper, and at the time need both of them to work. It there is a custom implementation use it, else fallback to AutoMapper.

The custom mapper looks something like this:

public static class CustomMapper
{
    public static Entity1DTO Map(Entity1 source){
        ... some mapping code ...
    }

    public static Entity2DTO Map(Entity2 source){
        ... some mapping code ...
    }

    ...
}

I need a way to check if the Map method excepts a specific type without checking for each type manually. I tried creating another overload which accepts object and returns object, but I don't know how to check if other overloads satisfy a specific type and call them.

Basically I want to make a generic wrapper method which will handle redirecting to CustomMapper or AutoMapper. Something like:

public static class Mapper
{
    public static T Map<T>(object source){
        return CustomMapper.Map(source) ?? AutoMapper.Map(source);
    }
}

So the question is how do I make a method in CustomMapper that will know if another Map method overload can handle the accepted type. If not return null or throw an exception, so I can fallback to AutoMapper in the wrapper.

1

There are 1 answers

2
Luaan On

Well, your custom mapper has simple static methods, so you can just take advantage of the usual overload resolution:

public static T Map<T>(Entity1 source) { ... }
public static T Map<T>(Entity2 source) { ... }
public static T Map<T>(EntityN source) { ... }

public static T Map<T>(object source) { ... }

The last method will be your AutoMapper fallback - used when there's no more direct overload.

To call this, you'd simply do CustomMapper.Map<DTOEntityX>(whateverValue). If you also need this to work with the realtime type of whateverValue, you can use dynamic - CustomMapper.Map<DTOEntityX>((dynamic)whateverValue); this will resolve the best overload at runtime.

When you're done with the transition, just remove the fallback method, and you're done.