Interfaces in C#: An Easy Learning

Interfaces in C#: An Easy Learning

21 Oct 2024
Advanced
151K Views
16 min read
Learn via Video Course & by Doing Hands-on Labs

Free C# Course Online

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

Q1. Can I use interfaces to achieve multiple inheritance in C#?

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.

Q2. How do I choose between using an interface or an abstract class in C#?

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.

Q3. Can I inherit from a class and an interface in C#?

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

Q4. Can I use interfaces to define custom attributes in C#?

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

Live Classes Schedule

Our learn-by-building-project method enables you to build practical/coding experience that sticks. 95% of our learners say they have confidence and remember more when they learn by building real world projects.
.NET Solution Architect Certification TrainingOct 26SAT, SUN
Filling Fast
05:30PM to 07:30PM (IST)
Get Details
.NET Microservices Certification TrainingOct 26SAT, SUN
Filling Fast
05:30PM to 07:30PM (IST)
Get Details
ASP.NET Core Certification TrainingOct 26SAT, SUN
Filling Fast
09:30AM to 11:30AM (IST)
Get Details
Advanced Full-Stack .NET Developer Certification TrainingOct 26SAT, SUN
Filling Fast
09:30AM to 11:30AM (IST)
Get Details
Azure Developer Certification TrainingOct 27SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details
Microsoft Azure Cloud Architect with AINov 10SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details

Can't find convenient schedule? Let us know

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

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 9th time in a row (2016-2024). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this