28
MarInterfaces in C#: An Easy Learning
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, a lot to understand it clearly.
To deepen your understanding of access specifiers and other C# concepts, be sure to enroll in our Free C # Course for a comprehensive learning experience.
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.
Read More: OOPs Interview Questions and Answers in C# |
How to create a C# Interface
To create an interface in C#, we use the interface keyword followed 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 an 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
Explanation
- In C#, a class can implement a single interface to ensure it follows a specific contract.
- An interface defines a set of methods and properties that the implementing class must provide.
- This promotes code reusability, abstraction, and loose coupling.
Example-2. Implementing multiple interfaces in C#
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
Explanation
- In C#, a class can implement multiple interfaces, allowing it to inherit behavior from different interface contracts.
- This is useful when a class needs to provide multiple functionalities that come from different sources.
- Unlike multiple inheritance (which is not supported in C#), multiple interfaces prevent ambiguity and keep the design clean
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!
Bark!
Meow!
Explanation
- In C#, an interface defines a contract that classes must follow by implementing its methods and properties.
- A reference variable of an interface can be used to hold a reference to any object of a class that implements the interface.
- This enables polymorphism, allowing a single interface reference to refer to objects of different classes that implement the interface.
Read More: Objects and Classes in C# |
Example-4. Demonstrating the basic case for implementing Interface
using System;
// Interface Definition
interface IAnimal
{
void Speak();
}
// Concrete Class Implementing Interface
class Dog : IAnimal
{
public void Speak()
{
Console.WriteLine("Dog barks: Woof Woof!");
}
}
class Cat : IAnimal
{
public void Speak()
{
Console.WriteLine("Cat meows: Meow Meow!");
}
}
// Main Class Demonstrating Polymorphism
class InterfacePolymorphismExample
{
static void MakeAnimalSpeak(IAnimal animal)
{
animal.Speak();
}
static void Main(string[] args)
{
IAnimal myDog = new Dog();
IAnimal myCat = new Cat();
MakeAnimalSpeak(myDog);
MakeAnimalSpeak(myCat);
}
}
Output
Dog barks: Woof Woof!
Cat meows: Meow Meow!
Explanation
- Interface Definition: IAnimal declares the method
Speak()
that must be implemented by any class using this interface. - Concrete Classes: Dog and Cat implement the
IAnimal
interface and provide their specific implementation of theSpeak()
method. - Polymorphism: The method
MakeAnimalSpeak(IAnimal animal)
demonstrates polymorphism by allowing different implementations of IAnimal (Dog and Cat) to be used interchangeably. - Real-Time Example: This simulates how different animals make different sounds, illustrating how interfaces and polymorphism allow flexible and scalable code design.
Example-5. Implementation of interfaces and the use of polymorphism in C#
using System;
// Interface Definition
interface IVehicle
{
void Drive();
}
// Concrete Class Implementing Interface
class Car : IVehicle
{
public void Drive()
{
Console.WriteLine("The car is driving.");
}
}
// Main Class
class InterfaceExample
{
static void Main(string[] args)
{
IVehicle myCar = new Car();
myCar.Drive();
}
}
Output
The car is driving.
Explanation
- Interface Definition: IVehicle declares the method
Drive()
that must be implemented by any class using this interface. - Concrete Class: Car implements the
IVehicle
interface and provides the actual implementation of theDrive()
method. - Main Class: InterfaceExample demonstrates the use of an interface by creating an instance of Car and calling the
Drive()
method.
Default interface members
Default Interface Members were introduced in C# 8.0 to allow interfaces to have method implementations. This feature enables developers to add new members to interfaces without breaking existing implementations.
An interface may include:
- Constants
- Operators
- Static constructor.
- Nested types
- Static fields, methods, properties, indexers, and events
- Member declarations using the explicit interface implementation syntax.
Static abstract and virtual members
Static, abstract, and virtual members with various capabilities are supported by interfaces in C#. Static methods and fields are examples of static members of interfaces, and derived classes are required to implement static abstract methods. Any class that inherits an interface must implement abstract members since they are the default in interfaces. Interfaces with virtual members can implement default methods, which derived classes can override if necessary.
Features of Interface
- 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.
- 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();
- C# interface contains only properties, indexers, methods, delegates, and event signatures.
- C# interface cannot contain constant members, constructors, instance variables, destructors, static members, or nested interfaces.
- Members of an interface in C# cannot have any access modifiers, not even the public.
- It is a good practice to start all interface names with a capital “I” letter.
Read More: New features added to C# 5.0 |
Common Design Guidelines for Interface
- 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.
- 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.
- 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?
- Need to provide common functionality to unrelated classes.
- Need to group objects based on common behaviors.
- Need to introduce polymorphic behavior to classes since a class can implement more than one interface.
- Need to provide a more abstract view of a model which is unchangeable.
- 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 the implementation.
Advantages of Interface in C#
- Loose Coupling: By reducing coupling between classes, interfaces enable the replacement or modification of one class without impacting the others.
- Polymorphism: Polymorphism, or the ability to consider objects of distinct classes as objects of a similar interface type, is made possible via interfaces.
- Abstraction: Interfaces offer abstraction by keeping implementation specifics hidden and only displaying the data that is required by the external world.
- Testability: Because they offer a precise contract for the intended behavior of a class, interfaces facilitate the writing of unit tests.
- Flexibility: Interfaces provide designers with more creative freedom since various classes can implement them in different ways.
- Reusability: Because a class that implements an interface may be used in many contexts, interfaces encourage code reusability.
Disadvantage of Interface in C#
- 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.
- Rigidity: Because modifications to an interface might affect all classes that implement it, interfaces have the potential to make a system more inflexible.
- 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.
- 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.
- 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 helps you in your programming journey.
Let the quiz begin! Pick the right answers and climb to the top!
Q 1: What is an interface in C#?
FAQs
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.