C# Interface – Understanding Interfaces in C# (With Examples)

C# is a popular object-oriented programming language used to develop different types of software applications. One of the key features of C# is the interface, which allows developers to define a contract for a class without specifying any implementation details.

This article will discuss the syntax, advantages, and implementation of C# interfaces, along with practical code examples.

CSharp Interface
C# Interface

C# Interface

An interface is a blueprint of a class that defines a set of methods, properties, and events that a class must implement. In C#, an interface is declared using the “interface” keyword, followed by the interface name and a list of members (methods, properties, and events) inside curly braces.

Interface in C# is a fundamental concept in object-oriented programming that defines a contract between a class and the outside world.

In C#, an interface resembles a class but doesn’t contain any implementation details. The main reason is that interfaces are designed to be inherited by classes and structs, which are then responsible for implementing each member declared in the interface.

Syntax for Interface Declaration:

The following code demonstrates the syntax for interface declaration in C#:

interface IExampleInterface
{
    void Method1();
    int Method2(string str);
    string Property1 { get; set; }
    event EventHandler MyEvent;
}

In the above example, we have declared an interface named IExampleInterface, which contains four members – two methods, one property, and one event. Note that interfaces cannot have access modifiers because all members of an interface are public by default.

Advantages of Interface in C#

Some of the key advantages of an Interface are:

  • Code Reusability: By using interfaces, we can create reusable code that multiple classes can implement. That reduces code duplication and makes our code more maintainable.
  • Loose Coupling: Interfaces allow us to achieve loose coupling between different components of our application. It means that changes made to one component will not affect the other components that use it.
  • Polymorphism: Interfaces allow us to achieve polymorphism in our code. It means we can write code that works with objects of different classes that implement the same interface.
  • Separation of Concerns: Interfaces allow developers to separate the definition of a contract from the implementation details. It allows for a clean separation of concerns and promotes better code maintainability and modularity.
  • Testability: Interfaces make it easier to test code by allowing developers to create mock objects that implement the same interface as the actual objects being tested. That helps to isolate and test individual components of a system.

How to Create an Interface in C#?

Creating an interface in C# is very simple. We just need to use the “:” colon followed by the interface name we want to implement. Here is an example:

For example, let’s define a class named Car that implements the IMovable interface:

class Car : IMovable
{
    public void Move()
    {
        // Implement the Move method
    }

    public int Speed { get; set; }
}

Now, we can create an object of the “Car” class and treat it as an object of the IMovable interface:

IMovable car = new Car();
car.Move();

How to Implement Multiple Interfaces?

A class in C# can implement multiple interfaces. To implement multiple interfaces, a class must list all the interfaces separated by commas after the “:” colon.

using System;
public interface IShape
{
    double GetArea();
}

public interface IColor
{
    string GetColor();
}
// Implementing multiple Interfaces
public class Rectangle : IShape, IColor
{
    private double length;
    private double width;
    private string color;

    public Rectangle(double length, double width, string color)
    {
        this.length = length;
        this.width = width;
        this.color = color;
    }

    public double GetArea()
    {
        return length * width;
    }

    public string GetColor()
    {
        return color;
    }
}

class Program
{
    static void Main(string[] args)
    {
        Rectangle rectangle = new Rectangle(5, 10, "Blue");
        Console.WriteLine("Area: " + rectangle.GetArea());
        Console.WriteLine("Color: " + rectangle.GetColor());

        Console.ReadKey();
    }
}

In the above example, we have two interfaces: IShape and IColor. The IShape interface defines a single method GetArea(), while the IColor interface defines a single method GetColor(). The Rectangle class implements both interfaces and provides implementations for both methods.

In the Main() method, we create a new instance of the Rectangle class and call the GetArea() and GetColor() methods on it, demonstrating that the class correctly implements both interfaces.

Output:

Area: 50
Color: Blue

Explicit Interface Implementation

In C#, we use explicit interface implementation to explicitly implement an interface member to avoid ambiguity when a class implements multiple interfaces having a member with the same name and signature.

By using explicit implementation, we can resolve the ambiguity between the members with the same name. The class must explicitly specify which interface member it is implementing.

Example:

Here is a simple full code example of explicit interface implementation in C#:

using System;

public interface IShape {
    void Draw();
}

public interface ICircle {
    void Draw();
}

public class Shape : IShape, ICircle {
    void IShape.Draw() {
        Console.WriteLine("Drawing a shape");
    }

    void ICircle.Draw() {
        Console.WriteLine("Drawing a circle");
    }
}

class Program {
    static void Main(string[] args) {
        IShape shape = new Shape();
        ICircle circle = new Shape();

        shape.Draw(); // Outputs "Drawing a shape"
        circle.Draw(); // Outputs "Drawing a circle"
    }
}

Default Interface Methods (C# 8.0)

Default interface methods are introduced in C# 8.0, which allows you to define default implementations of interface methods. 

This feature is useful when you want to add a new method to an existing interface without breaking the code that implements it.

A default method in an interface is similar to a regular method but has a default implementation. The default implementation provides a fallback behavior for the interface method if a class that implements the interface doesn’t provide its own implementation.

Here’s an example of how to declare a default method in an interface:

Example of Default Interface method:

using System;
public interface IExample
{
    void Print();
    
    // Default method implementation
    void SayHello()
    {
        Console.WriteLine("Hello, World!");
    }
}

public class Example : IExample
{
    public void Print()
    {
        Console.WriteLine("This is an example.");
    }
}

public class Program
{
    static void Main(string[] args)
    {
        Example ex = new Example();
        ex.Print();
        ex.SayHello();  // Calling the default method
    }
}

Learn more about default interface methods.

Modifiers in Interfaces (C# 8.0)

Starting with C# 8.0, interfaces can have access modifiers just like classes. The available access modifiers for interfaces are public, internal, protected internal, and private. These access modifiers control the visibility of the interface members to the outside world.

A public interface can be accessed from anywhere, whereas an internal interface can only be accessed from within the same assembly.

A protected internal interface can be accessed from within the same assembly and from derived types located in other assemblies. Finally, we can only access a private interface within the same class or struct.

Full example of all the access modifiers supported in C# Interface 8.0:

Let’s consider an example where we have an interface named IMyInterface with four methods, each with a different access modifier.

using System;
namespace InterfaceAccessModifiersExample
{
    public interface IExampleInterface
    {
        public void PublicMethod();

        void InternalMethod();

        protected void ProtectedMethod();

        private void PrivateMethod();

        static void StaticMethod()
        {
            Console.WriteLine("This is a static method in the interface");
        }
    }

    public class ExampleClass : IExampleInterface
    {
        public void PublicMethod()
        {
            Console.WriteLine("This is a public method implementation in the class");
        }

        void IExampleInterface.InternalMethod()
        {
            Console.WriteLine("This is an internal method implementation in the class");
        }

        protected void IExampleInterface.ProtectedMethod()
        {
            Console.WriteLine("This is a protected method implementation in the class");
        }

        private void IExampleInterface.PrivateMethod()
        {
            Console.WriteLine("This is a private method implementation in the class");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            ExampleClass obj = new ExampleClass();
            obj.PublicMethod();

            IExampleInterface iobj = obj;
            iobj.InternalMethod();

            ((IExampleInterface)obj).ProtectedMethod();

            // Compiler error, private method not accessible
            //((IExampleInterface)obj).PrivateMethod();

            // Calling a static method in the interface
            IExampleInterface.StaticMethod();
        }
    }
}

FAQs

Q: What is an interface in C#? 

An interface in C# is a blueprint of a class that defines a set of methods, properties, and events that the class implementing the interface must implement.

Q: Why should I use an interface in C#?

Interfaces in C# provide a way to achieve abstraction and decoupling between the components of your application, making it more modular, testable, and maintainable. They also facilitate polymorphism, allowing you to treat different objects that implement the same interface in a uniform way.

Q: Can a class implement multiple interfaces in C#?

Yes, a class in C# can implement multiple interfaces. It allows the class to have the functionality of all the interfaces it implements.

Q: Can I define an interface inside a class in C#?

Yes, you can define an interface inside a class in C#. That is called a nested interface, and it can only be accessed through an instance of the enclosing class.

You might also like:

Shekh Ali
4.5 2 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments