0

I am looking this code

interface IEven 
{
    bool IsOdd(int x);
    bool IsEven(int x);
}

class MyClass : IEven 
{
    bool IEven.IsOdd(int x) 
    {
        if((x%2) != 0) return true;
        else return false;
    }

    public bool IsEven(int x) 
    {
        IEven o = this;
        return !o.IsOdd(x);
    }
}

which explains difference between explicit and implicit interface implementation.

How to write interface reference to the invoking object without this?

Richard Rublev
  • 7,718
  • 16
  • 77
  • 121
  • In this specific case you could put the logic in `IsEven` and use that from `IsOdd`. – juharr Oct 19 '17 at 13:26
  • @MartinVerjans That's not allowed since it's an explicit implementation. – juharr Oct 19 '17 at 13:27
  • @MartinVerjans That won't compile. – Servy Oct 19 '17 at 13:27
  • @MartinVerjans Yes,won't compile for sure! – Richard Rublev Oct 19 '17 at 13:28
  • @RichardRublev You probably should include that in the question as many will not know about that compilation issue. – juharr Oct 19 '17 at 13:29
  • @juharr Martins's solution won't compile,mine question was how to get new solution without this. – Richard Rublev Oct 19 '17 at 13:31
  • I'm not sure I agree with the duplicate ("without casting" vs "without `this`"). I can't think of any way to avoid the `this` keyword here, you need to change your expression type from `MyClass` to `IEven`. The "duplicate" question lists all the forms you can use to achieve the dispatch; all involve the value keyword `this`. – bartonjs Oct 19 '17 at 13:34
  • `bool IEven.IsOdd(int x){ return !IsEven(x); } public bool IsEven(int x) { return x % 2 == 0; }`, but that's just for this case, otherwise you'll have to either do the casting or move the logic into a private method that both can use. – juharr Oct 19 '17 at 13:36

0 Answers0