My Software Notes

Useful things I discover

Archive for the ‘General Programming’ Category

Dispatching and Binding

leave a comment »

This is just a quick note on definitions:

Binding – determining which signature (method name + parameters) should be called.

Dispatching – Figuring out which implementation of a signature to call.

Example:

    public interface IFoo
    {
        void MyMethod(int id);
    }

    public class Foo : IFoo
    {
        public virtual void MyMethod(int id)
        {
            //whatever
        }
    }

    public class Bar : Foo
    {
        public override void MyMethod(int id)
        {
            //whatever else
        }
    }

    public class Tester
    {
        public void TestMe()
        {

            var array = new IFoo[] { new Foo(), new Bar() };

            foreach(var item in array)
            {
                item.MyMethod(42);
            }
        }
    }

How do you determine which MyMethod in the foreach loop is  to be called?

Binding – match the signatures – MyMethod(int)

Dispatching – figure out which implementation (Foo.MyMethod or Bar.MyMethod) to call

Static Binding or Dispatching – figure it out at compile time.

Dynamic Binding or Dispatching – figure it out at run time.

 

Written by gsdwriter

November 2, 2016 at 7:42 am