Search code examples
c#objectlate-binding

how to implement LateBinding in C#


I'm having a general class in that class i've written one method which should accept the object class's object as parameter.

the function is as follows-

protected void AddNewForm(object o )
{
    try
    {
        o.Show();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

and i'm calling this function from another classes . but when i call this function as-

Contact objContact=new Contact(); 
AddNewForm(objContact);

but it shows the error in that function. the error as-

'object' does not contain a definition for 'Show' and no extension method 'Show' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)

How to implement late binding in C# windows application?

thanks.


Solution

  • If you use .NET 4 you can use the new dynamic keyword:

    protected void AddNewForm(dynamic o)
    {
        try
        {
            o.Show();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
    

    If you don't use .NET 4 you will have to resort to reflection.
    It then would look something like this:

    protected void AddNewForm(object o)
    {
        try
        {
            o.GetType().GetMethod("Show", new Type[0]).Invoke(o, null);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
    

    But you really should consider using a common interface:

    interface IShowable
    {
        void Show();
    }
    
    class Contact : IShowable
    {
        public void Show() { /* ... */ }
    }
    
    protected void AddNewForm(IShowable o)
    {
        try
        {
            o.Show();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }