Call Method Overloads Based on Derived Type

I was creating a data access component that performed different operations based on the type of request that it received. In order to accommodate this, I have an abstract base request type defined, and handled requests derive from this type. Without getting too deep into why I had to do it this way, I had overloaded methods to which I needed to “route” an instance of the abstract class.

.NET 4 gives us an easy way to do this with the dynamic keyword. Consider the following example, which will correctly call the correct method overload:

void Main()
{
    MyBase obj = new MyOne();
    var p = new Printer();
    p.Print(obj);
}

public class Printer
{
    public void Print(MyBase item)
    {
        dynamic i = item;
        Print(i);
    }
    
    public void Print(MyOne item)
    {
        Console.WriteLine("Print(MyOne)");
    }
}

public abstract class MyBase
{
}

public class MyOne : MyBase
{
}

dynamic wasn’t introduced until .NET 4, though. So, if you have an older application, it may not be available to you. The good news is that you can accomplish the same goal by using reflection. It’s just as effective, but it’s a bit gnarlier.

public void Print(MyBase item)
{
    this.GetType()
        .GetMethod("Print", new[] { item.GetType() })
        .Invoke(this, new object[] { item });
}

So there you have it–two different ways to call method overloads based on object type!

Advertisement

Author: Adam Prescott

I'm enthusiastic and passionate about creating intuitive, great-looking software. I strive to find the simplest solutions to complex problems, and I embrace agile principles and test-driven development.

2 thoughts on “Call Method Overloads Based on Derived Type”

  1. So if I get the value of using this method, in this case the dynamic “i” is of type “MyOne” at runtime; but is that true as of when it’s instantiated or when it’s passed as an input parameter?

    I haven’t yet tried to use “dynamic”, but I’m going to assume that the type isn’t known until runtime so there’s no nice intellisense or the like.

    1. Right, the type is determined at runtime. You may have limited Intellisense. In the example above, for instance, it can be determined that i will be a type that derives from MyBase, so you may have access to public members of MyBase through Intellisense. (I have not tested/verified this.)

Leave a comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: