Get to know Interfaces - CSharp Custom Type

CSharp examples for Custom Type:interface

Introduction

An interface provides a specification rather than an implementation for its members.

Interface members are all implicitly abstract.

A class (or struct) can implement multiple interfaces.

An interface declaration provides no implementation for its members.

These members will be implemented by the classes and structs that implement the interface.

An interface can contain only methods, properties, events, and indexers.

Here is the definition of the IEnumerator interface, defined in System.Collections:

public interface IEnumerator
{
  bool MoveNext();
  object Current { get; }
  void Reset();
}

Interface members are always implicitly public and cannot declare an access modifier.

Implementing an interface means providing a public implementation for all its members:

internal class Countdown : IEnumerator
{
  int count = 11;
  public bool MoveNext() => count-- > 0;
  public object Current => count;
  public void Reset() { throw new NotSupportedException(); }
}

You can implicitly cast an object to any interface that it implements. For example:

IEnumerator e = new Countdown();                                                                   
while (e.MoveNext())
    Console.Write (e.Current);      // 109876543210                                                  
                                                                                                        

Related Tutorials