0

Can some one help me understand why this doesn't work:

public interface IInterface
{
    string GetString(string start);
    void DoSomething();
}

public class InterfaceImpl : IInterface
{
    string IInterface.GetString(string start)
    {
        return start + " okay.";
    }
    void IInterface.DoSomething()
    {
        Console.WriteLine(this.GetString("Go")); // <-- Error: InterfaceImpl does not contain a definition for GetString
    }
}

I can't figure out why I can't call a function that is most certainly defined in the implementation.

Thanks for your help.

1
  • Consider also reading interfaces overview on MSDN - you may not need explicit implementation as cruellays' answer points out. Commented Jul 23, 2014 at 1:34

2 Answers 2

5

Explicitly implemented methods need to be called on variable of interface type, usually with cast:

   Console.WriteLine(((IInterface)this).GetString("Go"));

More variants of calling explicitly defined methods are covered in How to call explicit interface implementation methods internally without explicit casting?

Sign up to request clarification or add additional context in comments.

Comments

5

you do not need to explicitly specify the Interface with the method. Since InterfaceImpl is already implementing IInterface, you just need to do as follows:

public class InterfaceImpl : IInterface
{
    public string GetString(string start)
    {
        return start + " okay.";
    }
    public void DoSomething()
    {
        Console.WriteLine(GetString("Go"));
    }
}

Updated as per comment.

1 Comment

Those methods should be marked public, otherwise this doesn't implement the interface.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.