locked
calling overloaded functions using generic paremeters RRS feed

  • Question

  • Is there a way to call functions with different signatures with generic objects?

    i.e.

    private void a (aobj obj){}

    private void a (bobj obj){}

    private foo()
    {
    ...
    private void a((object)new aobj());
    }

    Wednesday, February 9, 2011 4:16 PM

Answers

  • Overload resolution is made at compile-time. You must call the method with either an aobj argument or a bobj argument, not an object argument. You can delay the overload resolution using reflection:

    GetType().InvokeMember("a", BindingFlags.InvokeMethod, null, this, new object[] { new aobj() });
    
    As a side-note: avoid the use of the word "generic" when talking about non-generic features, it's confusing.
    • Proposed as answer by James Michael Hare Wednesday, February 9, 2011 4:57 PM
    • Marked as answer by Blue Baron Wednesday, February 9, 2011 6:02 PM
    Wednesday, February 9, 2011 4:48 PM

All replies

  • Overload resolution is made at compile-time. You must call the method with either an aobj argument or a bobj argument, not an object argument. You can delay the overload resolution using reflection:

    GetType().InvokeMember("a", BindingFlags.InvokeMethod, null, this, new object[] { new aobj() });
    
    As a side-note: avoid the use of the word "generic" when talking about non-generic features, it's confusing.
    • Proposed as answer by James Michael Hare Wednesday, February 9, 2011 4:57 PM
    • Marked as answer by Blue Baron Wednesday, February 9, 2011 6:02 PM
    Wednesday, February 9, 2011 4:48 PM
  • If you're just trying to call the first option, leave the (object) cast off:

     

       private void foo() {

         a(new aobj()); // This will call private void a(aobj obj) { ... }

         var b = new bobj();

         a(b); // This will call private void a(bobj obj) { ... }

       }

     

     


    Reed Copsey, Jr. - http://reedcopsey.com
    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".
    Wednesday, February 9, 2011 5:12 PM
  • lol.  The cast was not an option.  That was just sample code.  Really I'm getting an object and passing it on. lous.fr ftw.

    Wednesday, February 9, 2011 6:02 PM
  • You're getting an object and don't know if it's an aobj or a bobj?

    Try something like this instead:

    aobj objA = obj as aobj;
    if(objA != null)
    {
        a(objA);
    }
    else
    {
        bobj objB = obj as bobj;
        if(objB != null)
            a(objB);
    }
    

    Thursday, February 10, 2011 12:52 AM