C#: Interface

What is an interface?

Interface is a similar to a class it can contain properties, methods, events and indexers. Each member in an interface must have the public access modifier, and other access modifiers will not work with an interface. Interface do not contain any implementations, the only way to use an interface is by creating a subclass that implements the interface members.

public interface IDisplayMessage {
   public void Show();

How do you use an interface?

To use an interface you must create a subclass that inherits the interface and implement it’s members. For example below I have created a subclass called MyClass the implements the IDisplayMessage interface and it’s members. Inside the Show() method I write my own piece of code to output a text message to the console:

public class MyClass : IDisplayMessage {
   private string message;
   public MyClass() {
      message = "Hello, World!";
   public void Show() {
void Main() {
   MyClass myClass = new MyClass();

You can implicitly cast an object to any interface that it implements. For example below I am casting myClass to IDisplayMessage and still will be able to call the Show() method.

   IDisplayMessage displayMessage = new MyClass();


Interface is similar to a class, it contains public properties and methods with no implementation. Subclass my using an interface must implement all the members and object can be implicitly cast to an interface that it implements.