Search code examples
c#.netclassinterfaceimplementation

How can I call a method inherited from an interface directly from a class?


using System;

interface ISample{
  abstract void SampleMethod();
}

class SampleClass: ISample{
  void ISample.SampleMethod(){
    Console.WriteLine("SampleMethod was called.");
  }
}

class Program{
  public static void Main (string[] args){
    SampleClass smpcls = new SampleClass();
    smpcls.ISample.SampleMethod();
  }
}

This code works seamlessly. But I must call "ISample" interface from "smpcls" which is the instance of "SampleClass". How can I call "SampleMethod" directly from a instance of "SampleClass"?

For example:

...
SampleClass smpcls = new SampleClass();
smpcls.SampleMethod() //I would like to call it like this.
smpcls.ISample.SampleMethod() //Not like this
...

Solution

  • SampleClass explicitly implements ISample.SampleMethod, which is not what you want. Simply change it to

    class SampleClass: ISample{
      void SampleMethod(){
        Console.WriteLine("SampleMethod was called.");
      }
    }