Tibi
Tibi

Reputation: 3875

C# automatic casting when calling overloaded function

Let's imagine that I have the following overloaded function:

void DoSomething(int x) { ... }
void DoSomething(float x) { ... }
void DoSomething(decimal x) { ... }

In the following method, I need to call the correct overload. This is how a simple implementation would look like:

void HaveToDoSomething(object data)
{
    if (data is int) DoSomething((int)data);
    else if (data is float) DoSomething((float)data);
    else if (data is decimal) DoSomething((decimal)data);
}

This is tedious when there are ~20 types to check. Is there a better way of doing all this casting automatically?

Something I forgot to mention: DoSomething wouldn't work with generics, as each type needs to be handled differently, and I only know the type at runtime.

Upvotes: 1

Views: 285

Answers (2)

Michael
Michael

Reputation: 1096

You can use Reflection but it can have a performance impact:

public class Example
{
    void DoSomething(int i)
    {

    }

    void DoSomething(float i)
    {

    }
}

public static class ExampleExtensions
{
    public static void DoSomethingGeneric(this Example example, object objectParam)
    {
        var t = objectParam.GetType();
        var methods = typeof(example).GetMethods().Where(_ => _.Name == "DoSomething");
        var methodInfo = methods.Single(_ => _.GetParameters().First().ParameterType == t);
        methodInfo.Invoke(example, new[] { objectParam });
    }
}

Upvotes: 1

mjwills
mjwills

Reputation: 23898

One possible approach would be to use dynamic:

void HaveToDoSomething(dynamic data)
{
    DoSomething(data);
}

Upvotes: 2

Related Questions