DEV Community

mohamed Tayel
mohamed Tayel

Posted on

Mastering C# Fundamentals: Understanding Interfaces

Meta Description: Learn how to effectively use interfaces in C# to implement polymorphism through contracts and multiple interfaces, enhancing code flexibility and maintainability

In this article, we're going to dive into interfaces in C#. We will explore what interfaces are, why they are important, and how they help us apply polymorphism in a clean, structured manner. We’ll also cover an example of implementing multiple interfaces in a single class to showcase the power of composition in C#. Finally, you will have new assignments to test your understanding of these concepts.

What Are Interfaces?

In C#, interfaces are a crucial component of Object-Oriented Programming (OOP). An interface is essentially a contract. In real life, when you sign a contract, it binds you and another party to a set of rules. Similarly, in programming, an interface declares methods that an implementing class must provide. This helps maintain consistency across different classes, ensuring that they all share specific behaviors.

Why Are Interfaces Important?

Interfaces are powerful tools for achieving consistent implementation across classes. When a class implements an interface, it guarantees that it will have all the methods defined in the interface. This consistency makes your code flexible, maintainable, and extendable.

Additionally, interfaces enable polymorphism—a core concept of OOP. Polymorphism allows us to use a single interface to represent multiple underlying types. This makes code simpler to manage and modify, and easier to extend without breaking existing functionality.

Defining an Interface

Defining an interface in C# is similar to defining a class, with some key differences. Here’s how you can define a simple interface:

public interface IEmployee
{
    void PerformWork();
    void GiveBonus();
}
Enter fullscreen mode Exit fullscreen mode
  • Interfaces use the interface keyword.
  • By convention, interface names start with an "I" (e.g., IEmployee). This is not mandatory but helps distinguish interfaces from classes.
  • The interface only contains method signatures without any implementations, which guarantees that any implementing class will provide its own version of these methods.

Implementing an Interface

When a class implements an interface, it commits to providing concrete implementations for all of the interface's methods.

public class Employee : IEmployee
{
    public void PerformWork()
    {
        Console.WriteLine("Employee is performing work.");
    }

    public void GiveBonus()
    {
        Console.WriteLine("Employee received a bonus.");
    }
}
Enter fullscreen mode Exit fullscreen mode

If the class doesn't implement all the methods declared in the interface, the C# compiler will throw an error.

Multiple Interfaces in a Class

C# allows a class to implement multiple interfaces, which can be especially useful when you want your class to have multiple sets of related behaviors. Let's define another interface and implement both in a single class.

public interface IManager
{
    void ManageTeam();
    void ScheduleMeeting();
}
Enter fullscreen mode Exit fullscreen mode

We now have IEmployee and IManager interfaces. Let’s create a StoreManager class that implements both:

public class StoreManager : IEmployee, IManager
{
    public void PerformWork()
    {
        Console.WriteLine("StoreManager is performing managerial tasks.");
    }

    public void GiveBonus()
    {
        Console.WriteLine("StoreManager received a bonus.");
    }

    public void ManageTeam()
    {
        Console.WriteLine("StoreManager is managing the team.");
    }

    public void ScheduleMeeting()
    {
        Console.WriteLine("StoreManager has scheduled a team meeting.");
    }
}
Enter fullscreen mode Exit fullscreen mode

The StoreManager class provides implementations for all methods declared in both IEmployee and IManager.

Demonstrating Polymorphism with Multiple Interfaces

The beauty of interfaces is that we can use polymorphism to handle objects using their interface types. Let’s see how this works with the StoreManager:

public class Program
{
    public static void Main(string[] args)
    {
        StoreManager storeManager = new StoreManager();

        // Using the instance as IEmployee
        IEmployee employee = storeManager;
        employee.PerformWork();
        employee.GiveBonus();

        // Using the instance as IManager
        IManager manager = storeManager;
        manager.ManageTeam();
        manager.ScheduleMeeting();

        // Using StoreManager directly
        storeManager.PerformWork();
        storeManager.ManageTeam();
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

StoreManager is performing managerial tasks.
StoreManager received a bonus.
StoreManager is managing the team.
StoreManager has scheduled a team meeting.
StoreManager is performing managerial tasks.
StoreManager is managing the team.
Enter fullscreen mode Exit fullscreen mode

Explanation

  • The StoreManager class implements both IEmployee and IManager, which means it must provide implementations for all the methods from both interfaces.
  • We can assign a StoreManager object to an IEmployee or IManager reference, demonstrating polymorphism.
  • This approach allows us to treat the StoreManager instance as either an employee or a manager, depending on our context.

Conclusion

Interfaces in C# are a powerful tool for ensuring consistent behavior across classes and enabling polymorphism. By allowing multiple interfaces to be implemented by a single class, C# provides a way to add modularity and flexibility to code without resorting to complex inheritance hierarchies.

Assignments

To reinforce your understanding of interfaces and their use in polymorphism, try the following exercises:

Easy Level

  1. Create two simple interfaces:
    • ICar with methods StartEngine and StopEngine.
    • IMaintainable with methods Service and Inspect.
  2. Create a class Sedan that implements both ICar and IMaintainable.
  3. Write a short program to create an instance of Sedan and call all the methods using both interfaces.

Medium Level

  1. Create two interfaces:
    • IAnimal with methods MakeSound and Move.
    • IPet with a method Play.
  2. Create classes Dog and Cat that implement both IAnimal and IPet.
  3. Write a program that creates a list of IPet objects and calls Play, MakeSound, and Move for each object.

Difficult Level

  1. Create two interfaces:
    • IBankAccount with methods Deposit, Withdraw, and CalculateInterest.
    • IInsurable with methods Insure and GetInsuranceQuote.
  2. Create classes SavingsAccount, CheckingAccount, and FixedDepositAccount that implement both IBankAccount and IInsurable. Each class should have specific rules for the methods.
  3. Write a program that creates different types of bank accounts and performs transactions using the IBankAccount and IInsurable interface references, demonstrating polymorphic behavior.

By working through these assignments, you'll understand the power of interfaces in enforcing consistent behavior and applying polymorphism in C#. Happy coding!

Top comments (0)