Question

Is there a formal name for what I've outlined below. The example is in c#, but the premise would apply to other langs. I'm almost certain I've done something like this years ago in some other lang, but what one, or the name of the concept escapes me. dynamic dispatch(of sorts)??

The key point I'm trying to convey, is that at runtime, the method to execute is determined, and called. The methods would have almost same signature, only differing by the type of the argument, and that the arguments are all in the same inheritance tree too. I know there are some details I've left out, but I want to keep the example simple.

string result;
User u;
User user = new User();
Manager manager = new Manager();

u = user;
result = _Print(u);
Console.WriteLine(result); // user...

u = manager;
result = _Print(u);
Console.WriteLine(result); // manager...

// interested in part
private static string _Print(User u)
{
    return (u is Manager) ? Print((Manager)u) : Print(u);
}

// plumbing
private static string Print(User u)
{
    return "User...";
}
private static string Print(Manager m)
{
    return "Manager...";
}

class User { ... }
class Manager : User { ... }
Was it helpful?

Solution

It is dynamic dispatch. I learn it as dynamic binding, because it is a function binding feature provided by many OO languages such as Java, that implements it by default, and C++, in which it requires in the explicit keyword "virtual" for it to work in a dynamic fashion - by default c++ is static binding. However, modern in OO the dynamic binding is easily achieved by Polimorphism and Overloading. So you can have something like this:

User u = new User(); 
Console.WriteLine(u.print()); // user...

u = new Manager();
Console.WriteLine(u.print()); // manager...


class User { ... 
    public string print(User u)
    {
        return "User...";
    }
... }
class Manager : User { ... 
    public string print(Manager m)
    {
        return "Manager...";
    }

... }

But you need to adapt to your language. I do not know much about C# and there are so many idiosyncrasies. I found this post with some examples for you - http://www.codeproject.com/KB/cs/dynamicbindingincsharp.aspx

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top