Interfaces in C#: An Easy Learning

Interfaces in C#: An Easy Learning

21 Oct 2024
Advanced
151K Views
16 min read
Learn with an interactive course and practical hands-on labs

Free C# Foundation Course: Learn C# In 21 Days

C# Interface

C# interfaces act like blueprints, telling a class what it needs to do without specifying how to do it. When a class implements an interface in C#, it promises to include the methods and properties defined by the C# interface but decides how to handle them. This keeps your code organized and flexible, allowing different classes to work together smoothly.

In this C# Tutorial, we will explore more about what is Interface in C#, including c# interface with real-life examples, when to use C# interface with examples, design guidelines for Interface in C#, the advantages and disadvantages of interfaces in C#, and many more. If you are a beginner in C# programming, C# Developer Roadmaphelps you a lot to understand it clearly.

What is the interface in c#?

Let's understand the C# interface by some points that make it easy to understand:

  • C# interface looks like a class, but It has no implementation.
  • C# Interface only contains declarations of events, indexers, methods, and/or properties.
  • The reason behind this is that interfaces are inherited by structs and classes, which must provide an implementation for each interface member declared.
  • The interface in C# is a completely abstract class.
  • C# Interface only contains abstract methods and properties.

How to create a C# Interface

To create an interface in C#, we use the interface keywordfollowed by the interface name and a collection of methods and properties.

Syntax of interface

 // interface
interface IMyInterface
{
  void employeename(); // interface method (does not have a body)
  void salary(); // interface method (does not have a body)
}   

How to implement C# Interface

To implement the C# interface, we use the(:)operator followed by the interface name. Next, every method and property specified in the C# interface must have an implementation provided by the class.

 class MyClass : IMyInterface
{
    public void MyMethod()
    {
        // Implementation details here
    }
    public int MyProperty { get; set; }
}  

Inheritance of Interface

We can also inherit interface from the other interfaces like:

 interface IMyBaseInterface
{
    void MyBaseMethod();
}
interface IMyDerivedInterface : IMyBaseInterface
{
    void MyDerivedMethod();
} 

Note: A class can use multiple interfaces by using commas(,).

 class MyClass : IMyInterface1, IMyInterface2
{
    // Implementation details here
}   

Real-World Example of Interface

Let's elaborate on the real-world example in C# Compiler.

Example-1. A Single Interface Used by a Class

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace HelloWorld
{
	interface ICompany
{
  void companyname(); // interface method (does not have a body)
}

class Employee : ICompany
{
  public void companyname() 
  {
    
    Console.WriteLine("Scholarhat");
  }
}

class Program 
{
  static void Main(string[] args) 
  {
    Employee emp = new Employee();  // Create a Employee object
    emp.companyname();
  }
}
}    

Output

 Scholarhat 

Example-2. Implementing multiple interfaces

 using System;

namespace MyFamily
{
  interface ImotherInterface
  {
    void Mother(); // interface method
  }

  interface IFatherInterface
  {
    void Father(); // interface method
  }

  // Implement multiple interfaces
  class ChildClass : ImotherInterface,IFatherInterface
  {
    public void Mother()
    {
      Console.WriteLine("Mother's DNA");
    }
    public void Father()
    {
      Console.WriteLine("Father's DNA");
    }
  }

  class Program
  {
    static void Main(string[] args)
    {
      ChildClass child = new ChildClass();
      child.Mother();
      child.Father();
    }
  }
}

Output:

 Mother's DNA
Father's DNA

Example-3. Using reference variable of an interface in C#

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

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

// Another class implementing the same interface
public class Cat : IAnimal
{
    public void MakeSound()
    {
        Console.WriteLine("Meow!");
    }
}

class Program
{
    static void Main(string[] args)
    {
        // Interface reference variable
        IAnimal myAnimal;

        // Assigning Dog object to the interface reference
        myAnimal = new Dog();
        myAnimal.MakeSound();  // Output: Bark!

        // Assigning Cat object to the same interface reference
        myAnimal = new Cat();
        myAnimal.MakeSound();  // Output: Meow!
    }
}   

Output
 Bark!
Meow! 

Features of Interface

  1. C# interface doesn't provide inheritance like a class or abstract class, but it only declares members to which an implementing class needs to be implemented.

  2. Inheritance in C# cannot be instantiated, but it can be referenced by the class object which implements it. Also, Interface reference works just like object reference and behaves like an object.

     IStore IObjStore = new Document();
    ICompress IObjCompress = new Document();
    
  3. C# interface contains only properties, indexers, methods, delegates, and event signatures.

  4. C# interface cannot contain constant members, constructors, instance variables, destructors, static members, or nested interfaces.

  5. Members of an interface in C# cannot have any access modifiers, not even the public.

  6. It is a good practice to start all interface names with a capital “I” letter.

Common Design Guidelines for Interface

  1. Keep your interfaces focused on the problem you are trying to solve and keep related tasks (methods) in an interface. Interfaces in C# that have multiple unrelated tasks tend to be very difficult to implement in a class. Split up interfaces that contain unrelated functionality.

  2. Make sure your interface does not contain too many methods. Too many methods make implementing the interface difficult, as the implementing class has to implement each and every method in the interface.

  3. Don't make interfaces for specific functionality. An interface should define the common functionality that can be implemented by the classes of different modules or subsystems.

When to use interfaces?

  1. Need to provide common functionality to unrelated classes.

  2. Need to group objects based on common behaviors.

  3. Need to introduce polymorphic behavior to classes since a class can implement more than one interface.

  4. Need to provide a more abstract view of a model which is unchangeable.

  5. Need to create loosely coupled components, easily maintainable and pluggable components (like log4net framework for logging) because the implementation of an interface is separated from itself.

Advantages of Interface in C#

  1. Loose Coupling: By reducing coupling between classes, interfaces enable the replacement or modification of one class without impacting the others.

  2. Polymorphism: Polymorphism, or the ability to consider objects of distinct classes as objects of a similar interface type, is made possible via interfaces.

  3. Abstraction: Interfaces offer abstraction by keeping implementation specifics hidden and only displaying the data that is required by the external world.

  4. Testability: Because they offer a precise contract for the intended behavior of a class, interfaces facilitate the writing of unit tests.

  5. Flexibility: Interfaces provide designers with more creative freedom since various classes can implement them in different ways.

  6. Reusability: Because a class that implements an interface may be used in many contexts, interfaces encourage code reusability.

Disadvantage of Interface in C#

  1. Over-Engineering: Interfaces may result in over-engineering, which increases the number of interfaces built into the system and increases its complexity and maintenance burden.

  2. Rigidity: Because modifications to an interface might affect all classes that implement it, interfaces have the potential to make a system more inflexible.

  3. Multiple Inheritance in C#: Although multiple class inheritance is not supported by C#, comparable functionality may be achieved by using interfaces, which can result in a complicated hierarchy of interfaces.

  4. Implicit Implementation: Interfaces can result in implicit implementation, which makes the code more difficult to comprehend when a class implements an interface without saying so out loud.

  5. Verbosity: Because interfaces must be explicitly implemented by every member, even if they are not utilized, they might introduce verbosity into the code.

Read More:
OOPs Interview Questions and Answers in C#

Conclusion:

In conclusion, I hope you have learned everything about the interface in C# now. To get the most out of C# interfaces, use them to define contracts, enable polymorphism, and improve testability while avoiding over-engineering and multiple inheritance issues. By using interfaces wisely, you can create more maintainable, scalable, and efficient software systems. for mastering C# programming language, Scholarhat provides a Full-Stack .NET Developer Certification Training Course that help you in your programming journey.

FAQs

Yes, interfaces can be used to achieve similar functionality to multiple inheritance in C#, but it's not recommended as it can lead to a complex hierarchy of interfaces.

Use an interface when you want to define a contract that must be implemented by any class that implements it, and use an abstract class when you want to provide a partial implementation of a class.

Yes, in C#, a class can inherit from a base class and implement one or more interfaces.

Yes, interfaces in C# can define custom attributes, which provide a way to decorate classes, methods, and properties with additional metadata.

Take our Csharp skill challenge to evaluate yourself!

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.

GET FREE CHALLENGE

Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan, Founder and CEO of ScholarHat by DotNetTricks, is a renowned expert in System Design, Software Architecture, Azure Cloud, .NET, Angular, React, Node.js, Microservices, DevOps, and Cross-Platform Mobile App Development. His skill set extends into emerging fields like Data Science, Python, Azure AI/ML, and Generative AI, making him a well-rounded expert who bridges traditional development frameworks with cutting-edge advancements. Recognized as a Microsoft Most Valuable Professional (MVP) for an impressive 9 consecutive years (2016–2024), he has consistently demonstrated excellence in delivering impactful solutions and inspiring learners.

Shailendra’s unique, hands-on training programs and bestselling books have empowered thousands of professionals to excel in their careers and crack tough interviews. A visionary leader, he continues to revolutionize technology education with his innovative approach.
Accept cookies & close this