05
JanInterfaces in C#: An Easy Learning
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!
Bark!
Meow!
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.
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 itself.
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 help you in your programming journey.
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.