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.

tanbla
  • 1
  • Consider also reading [interfaces overview](http://msdn.microsoft.com/en-us/library/ms173156.aspx) on MSDN - you may not need explicit implementation as cruellays' answer points out. – Alexei Levenkov Jul 23 '14 at 01:34

2 Answers2

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?

Community
  • 1
  • 1
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
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.

Yuan Shing Kong
  • 674
  • 5
  • 15
  • 1
    Those methods should be marked `public`, otherwise this doesn't implement the interface. – Kyle Jul 23 '14 at 02:27