C# - Interfaces



An interface is defined as a syntactical contract that all the classes inheriting the interface should follow. The interface defines the 'what' part of the syntactical contract and the deriving classes define the 'how' part of the syntactical contract.

Interfaces define properties, methods, and events, which are the members of the interface. Interfaces contain only the declaration of the members. It is the responsibility of the deriving class to define the members. It often helps in providing a standard structure that the deriving classes would follow.

Abstract classes to some extent serve the same purpose, however, they are mostly used when only few methods are to be declared by the base class and the deriving class implements the functionalities.

Declaring Interfaces

Interfaces are declared using the interface keyword. It is similar to class declaration. Interface statements are public by default. Following is an example of an interface declaration −

public interface ITransactions {
   // interface members
   void showTransaction();
   double getAmount();
}

Example of Implementing C# Interface

Let's see a basic example of the interface, where an animal interface states how an animal makes sound −

using System;
namespace InterfaceExample {
   // Define an interface
   public interface IAnimal {
      void MakeSound();
   }

   // Implement the interface in a class
   public class Dog : IAnimal {
      public void MakeSound() {
         Console.WriteLine("Dog barks: Woof Woof!");
      }
   }

   class Program {
      static void Main(string[] args) {
         Dog myDog = new Dog();
         myDog.MakeSound(); 
         Console.ReadKey();
      }
   }
}
Dog barks: Woof Woof!

Another Example

Let's see another example of the interface, which manages the transaction using the classes and interface −

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System;
namespace InterfaceApplication {  
   public interface ITransactions {
      // interface members
      void showTransaction();
      double getAmount();
   }
   public class Transaction : ITransactions {
      private string tCode;
      private string date;
      private double amount;
      
      public Transaction() {
         tCode = " ";
         date = " ";
         amount = 0.0;
      }
      public Transaction(string c, string d, double a) {
         tCode = c;
         date = d;
         amount = a;
      }
      public double getAmount() {
         return amount;
      }
      public void showTransaction() {
         Console.WriteLine("Transaction: {0}", tCode);
         Console.WriteLine("Date: {0}", date);
         Console.WriteLine("Amount: {0}", getAmount());
      }
   }
   class Tester {
     
      static void Main(string[] args) {
         Transaction t1 = new Transaction("001", "8/10/2012", 78900.00);
         Transaction t2 = new Transaction("002", "9/10/2012", 451900.00);
         
         t1.showTransaction();
         t2.showTransaction();
         Console.ReadKey();
      }
   }
}

When the above code is compiled and executed, it produces the following result −

Transaction: 001
Date: 8/10/2012
Amount: 78900
Transaction: 002
Date: 9/10/2012
Amount: 451900

C# Interface Types

Some of the interface types in C# include.

  • IEnumerable − Base interface for all generic collections.
  • IList − A generic interface implemented by the arrays and the list type.
  • IDictionary − A dictionary collection.

IEnumerable is an interface defining a single method GetEnumerator that returns an IEnumerator interface.

This works for readonly access to a collection that implements that IEnumerable can be used with a foreach statement.

Example of IEnumerable Interface

The following shows the implementation of IEnumerable interface:

using System;
using System.Collections;

class Demo : IEnumerable, IEnumerator
{
    private int[] numbers = { 1, 2, 3, 4, 5 };
    private int currentIndex = -1;

    // IEnumerable method GetEnumerator()
    public IEnumerator GetEnumerator()
    {
        return this; // Returns the current instance for iteration
    }

    // IEnumerator method - Current property
    public object Current
    {
        get
        {
            if (currentIndex == -1 || currentIndex >= numbers.Length)
                throw new InvalidOperationException();
            return numbers[currentIndex];
        }
    }

    // IEnumerator method - MoveNext
    public bool MoveNext()
    {
        if (currentIndex < numbers.Length - 1)
        {
            currentIndex++;
            return true;
        }
        return false;
    }

    // IEnumerator method - Reset
    public void Reset()
    {
        // Reset index to start iteration 
		// from the beginning
		currentIndex = -1; 
    }
}

class Program
{
    static void Main(string[] args)
    {
        Demo demo = new Demo();
        
        foreach (var number in demo)
        {
            Console.WriteLine(number);
        }
    }
}

When the above code is compiled and executed, it produces the following result −

1
2
3
4
5

Example of IList Interface

The following shows the implementation of IList interface:

using System;
using System.Collections.Generic;

class IListExample
{
    static void Main(string[] args)
    {
        // Create a list of integers
        IList<int> numbers = new List<int> { 1, 2, 3, 4, 5 };

        // Accessing elements by index
        Console.WriteLine("Element at index 2: " + numbers[2]); // Output: 3

        // Adding an element to the list
        numbers.Add(6);
        Console.WriteLine("Added 6 to the list.");

        // Removing an element from the list
        numbers.Remove(3); // Removes the first occurrence of 3
        Console.WriteLine("Removed 3 from the list.");

        // Iterating over the list
        Console.WriteLine("Updated list:");
        foreach (var num in numbers)
        {
            Console.WriteLine(num);
        }
    }
}

When the above code is compiled and executed, it produces the following result −

Element at index 2: 3
Added 6 to the list.
Removed 3 from the list.
Updated list:
1
2
4
5
6

Example of IDictionary Interface

The following shows the implementation of IDictionary interface:

using System;
using System.Collections.Generic;

class IDictionaryExample
{
    static void Main(string[] args)
    {
        // Create a dictionary with string keys and int values
        IDictionary<string, int> ages = new Dictionary<string, int>();

        // Adding key-value pairs to the dictionary
        ages.Add("Sudhir Shamra", 27);
        ages.Add("Prakash", 26);
        ages.Add("Yash", 22);

        // Accessing values using keys
        Console.WriteLine("Yash's age: " + ages["Yash"]); // Output: 30

        // Checking if a key exists
        if (ages.ContainsKey("Prakash"))
        {
            Console.WriteLine("Prakash's age is in the dictionary.");
        }

        // Iterating over the dictionary
        Console.WriteLine("List of people and their ages:");
        foreach (var kvp in ages)
        {
            Console.WriteLine($"{kvp.Key}: {kvp.Value}");
        }

        // Removing an entry
        ages.Remove("Yash");
        Console.WriteLine("Removed Yash from the dictionary.");

        // Checking the updated dictionary
        Console.WriteLine("Updated list of people and their ages:");
        foreach (var kvp in ages)
        {
            Console.WriteLine($"{kvp.Key}: {kvp.Value}");
        }
    }
}

When the above code is compiled and executed, it produces the following result −

Yash's age: 22
Prakash's age is in the dictionary.
List of people and their ages:
Sudhir Shamra: 27
Prakash: 26
Yash: 22
Removed Yash from the dictionary.
Updated list of people and their ages:
Sudhir Shamra: 27
Prakash: 26
Advertisements