Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Interface issue with function scope

Tags:

c#

interface

I have an interface as below:

public interface IInterface
{
    void Open();
    void Open(bool flag);
    void Open(bool flag, bool otherFlag);
}

Now when implementing the interface I have the following:

public class IClass : IInterface
{
    void IInterface.Open()
    {
        Open(false, false);
    }

    void IInterface.Open(bool flag)
    {
        Open(flag, false);
    }

    void IInterface.Open(bool flag, bool otherFlag)
    {
         //Do some stuff
    }
}

Now, the problem I am encountering is that within the first two function bodies in the IClass, I cannot call the third function. I get the error:

The name 'Open' does not exist in the current context

Okay, so I'm implementing the interface explicitly (due to a requirement from another team in the organization) and then I get the 'Open' context issue. I can remove the explicit IInterface from the three open methods, and then I can successfully compile, even with the other methods (not listed here) implemented explicitly, but I am not sure what the implications of this are.

Is there a way to call the third method while explicitly implementing the interface methods?

Thanks!

like image 562
Daniel Retief Fourie Avatar asked Dec 15 '22 09:12

Daniel Retief Fourie


1 Answers

Explicit implementations require using a reference of the interface type directly, even inside the implementing class:

    void IInterface.Open()
    {
        (this as IInterface).Open(false, false);
    }

    void IInterface.Open(bool flag)
    {
        (this as IInterface).Open(flag, false);
    }

Another way to retain the explicit implementation is to delegate calls to a private method:

    private void Open(bool flag, bool otherFlag)
    {
        // Do some stuff.
    }

Your calls will now map to this method:

    void IInterface.Open()
    {
        Open(false, false);
    }
    void IInterface.Open(bool flag)
    {
        Open(flag, false);
    }
    void IInterface.Open(bool flag, bool otherFlag)
    {
        Open(true, true);
    }

Also note that your class name goes against convention, remove the I prefix.

like image 91
Adam Houldsworth Avatar answered Dec 24 '22 01:12

Adam Houldsworth