- C# and Java: Two Sides of the Same Coin?
- A Simple C# Interface
- C# Interfaces and Inheritance
- Conclusion
A Simple C# Interface
Listing 1 illustrates probably the simplest C# interface.
Listing 1 A C# interface.
public interface IMyInterface { void DoSomething(); } class MainClass : IMyInterface { public void DoSomething() { Console.WriteLine("Now doing something"); Console.ReadLine(); } public static void Main(string[] args) { Console.WriteLine("Hello World!"); MainClass mainClass = new MainClass(); mainClass.DoSomething(); } }
In Listing 1, the MainClass class is said to implement the IMyInterface interface. This means that an instance of MainClass must provide an implementation of all the methods defined in the interface. In this context, an interface is often described as a contract. Any code that wants to use the interface must fulfill the requirements of the contract; that is, implement all the methods. In this example, the MainClass class must implement the methods of the IMyInterface interface—in this case, one method: DoSomething().