locked
Method overload does not work for WinRT Component in WinJS

    Question

  • It seems to me that the method overload does not work in WinRT Component for WinJS. For example, "void TestMethod(int i)" and "void TestMethod(Platform::String ^ i)" will be treated as "void TestMethod(int i)"

    Here is the simple sample to verify this problem:

    1. I define a public ref class with two overload methods

    namespace WindowsRuntimeComponent
    {
     public ref class TestClass sealed
        {
        public:
            TestClass();
      void TestMethod(int i);
      void TestMethod(Platform::String ^ i);
        };
    };

    2. In WinJS, both methods are called:

        var testObj = new WindowsRuntimeComponent.TestClass();
        testObj.testMethod(12);
        testObj.testMethod("hellow"); 

    3. Result: The debug shows that while WinJS calls "testObj.testMethod("hellow"); ", it actually calls "void TestMethod(int i);".

    Friday, July 13, 2012 6:40 PM

Answers

  • This behavior is expected.  Javascript only supports overloading based on arity, so it does not support calling multiple overloads with the same number of parameters.  In these cases, you should use the DefaultOverloadAttribute to specify which one should be callable from JS.  This is covered in more detail in the "Overloaded Methods" sections of:

    If you need to support a pattern like the above, consider not using overloads (i.e rename your methods TestMethodInt/TestMethodString), or use a type that will accept any of the types you want to support.  In this case, such a type would be IInspectable, or object (in C#).

    • Marked as answer by Renjie Huang Friday, July 13, 2012 9:45 PM
    Friday, July 13, 2012 7:39 PM