1

I have a class that implements the interface IPerson. I wanna call form my class a method implemented in the interface, and I get this error: CS0103 The name 'SayMyName' does not exist in the current context How can I call a method implemented in an interface from a derived class?

public interface IPerson
{
    string SayMyName()
    {
        return "MyName";
    }
}

public class Person : IPerson
{
    public void Method()
    {
        SayMyName();//ERROR CS0103 The name 'SayMyName' does not exist in the current context
    }
}
satellite satellite
  • 893
  • 2
  • 10
  • 27
  • 3
    Interfaces don't implement anything – Danny Apr 16 '21 at 17:12
  • 5
    @Danny They can now. See https://devblogs.microsoft.com/dotnet/default-implementations-in-interfaces/ – mason Apr 16 '21 at 17:14
  • 2
    Huh. What will they think of next? In *my* day we called those abstract classes.... :D – Danny Apr 16 '21 at 17:16
  • There are no derived classes in the sample code... Only an interface and a class *implementing* this interface, and the interface has a method with *default implementation*... So if duplicate is not enough check out other search results for correct terms https://www.bing.com/search?&q=c%23+call+default+method+interface%20site:stackoverflow.com and [edit] question using proper terms. – Alexei Levenkov Apr 16 '21 at 17:29

1 Answers1

6

You need explicit cast to access default implementation, provided by the interface.

((IPerson)this).SayMyName();
Serg
  • 3,454
  • 2
  • 13
  • 17