Interfaces in C#

Interfaces are basically a contract between the classes that implement the interface. Interfaces specify that a class must contain these members. However and interface do not provide implementation for its members. The class that implements the interface provides the definition for the interface members. In simple words, the “what” part of the contract is contained by the interface and the “how” part of the contract is implemented by the class.

´╗┐using System;
namespace CSharpTutorials {

    public interface IMessageDisplay {
       void Message1();
        int add(int a, int b);
        void DisplayString(string s);

    public class Messages: IMessageDisplay {
        public void Message1() {
            Console.WriteLine("Some random message.");
        public int add(int n1, int n2) {
            return n1 + n2;
        public void DisplayString(string a) {

    class Tutorial {
        static void Main(string[] args) {
            Messages msg = new Messages();
            msg.DisplayString("this is a message");
            Console.WriteLine(msg.add(150, 200));

Download the code

In the above code, an interface IMessageDisplay has been defined. Interfaces are defined like classes, however for interfaces, the keyword interface is used. The IMessageDisplay interface declared in the above code has three methods Message1, Add and DisplayString. These methods do not contain any implementation. Next, a class Messages has been declared which implements this IMessageDisplay interface. The Messages class has to implement the Message1, Add and DisplayString methods and provide its implementation. A class implements message using a “:” which was the case with inheriting from other classes.

<<< Inheritance in C#Polymorphism in C# >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .