1

How could I access I1 and I2 interfaces methods through I3 interface. I want to implement I3 in TestIt class (public class TestIt:I3). Do not want to implement I1 and I2 (public class TestIt:I1,I2).

My code is as below...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for TestIt
/// </summary>
public class TestIt:I3
{
    public TestIt()
    {
        //
        // TODO: Add constructor logic here
        //
        //TestItB tb = new TestItB();
    }

    public int abc()
    {
        return 10;
    }

    int I1.A1()
    {
        return 20;
    }

    void I2.A1()
    {
        int j = 0;
    }
}

public interface I1
{
   int A1();
}

public interface I2
{
    void A1();
}

public interface I3 : I1, I2
{

}

And I try to call A1 method as below...

I3 t = new TestIt();
int i = t.A1();

above is throw error...

I do not want to create object as blow...

I1 t = new TestIT(); 
   or 
I2 t = new TestIT();
Vishal Patel
  • 953
  • 5
  • 11
  • **What** error? Post the exception message. – Tom W Dec 02 '13 at 16:04
  • it doesn't know which one to call, as A1 is implemented twice. You'd need to vary the parameter types to A1 in order to differentiate the interface methods. – ps2goat Dec 02 '13 at 16:10
  • Error : The call is ambiguous between the following methods or properties: 'I1.A1()' and 'I2.A1()' – Vishal Patel Dec 02 '13 at 16:12
  • The call is wrong it gives error "explicit interface declaration can only be declared in a class or struct" in the below line it gives the error: int I1.A1(); void I2.A1(); – Vaibhav Parmar Dec 02 '13 at 16:20
  • The above question already asked please see this url: http://stackoverflow.com/questions/7080861/c-sharp-interface-method-ambiguity – Vaibhav Parmar Dec 02 '13 at 16:27
  • 1
    @VaibhavParmar My question is differ from this question (your posted URL). In your URL the both interface functions are same (return type, name and number of parameters) and in my question the both function return type is differ (one is INT and another is VOID). – Vishal Patel Dec 04 '13 at 10:47

1 Answers1

2

Cast the object to the appropriate interface type:

int i = ((I1)t).A1();

You can also do with with the as operator with (t as I1).A1(), although IMO casting gives a clearer indication of what's going on.

Jon
  • 428,835
  • 81
  • 738
  • 806
  • But I can't call A1 method by direct calling (without any type casting)? – Vishal Patel Dec 02 '13 at 16:28
  • @VishalPatel: No, because `TestIt` implements `I1.A1` explicitly. See http://msdn.microsoft.com/en-us/library/ms173157.aspx – Jon Dec 02 '13 at 16:30