In C# programming, an interface serves as a template for a class or struct. The interface keyword is employed to establish this template. Comparable to an abstract class, all methods declared within the interface are abstract. It encompasses multiple method sets, properties, events, and indexers.
Interfaces do not contain method implementations and are incapable of being instantiated directly. They serve the purpose of abstraction and enabling multiple inheritance, which is not possible with classes alone. The actual implementation of an interface must be supplied by a class or a struct. Any class or struct that implements an interface is required to furnish implementations for all the methods defined within that interface.
Interfaces in C# 8.0 and newer versions have the ability to contain default implementations and static members. This feature enhances the flexibility in designing software solutions.
Syntax of the Interface
It has the following syntax:
interface InterfaceName
{
// Method signature (no body)
void MethodName();
// Property signature
int PropertyName { get; set; }
// Event
event EventHandler EventName;
}
In this syntax,
- interface InterfaceName: It represents the name of the interface.
- void MethodName: It represents the name of the method without implementation.
- PropertyName: It represents the name of the property with get and set accessors.
- EventHandler, EventName: It is used to declare an event inside the interface.
C# Interface Example
Let's consider an example to demonstrate the interface in C#.
Example
using System;
public interface Drawable
{
void draw();
}
public class Rectangle : Drawable
{
public void draw()
{
Console.WriteLine("drawing rectangle...");
}
}
public class Circle : Drawable
{
public void draw()
{
Console.WriteLine("drawing circle...");
}
}
public class TestInterface
{
public static void Main()
{
Drawable d;
d = new Rectangle();
d.draw();
d = new Circle();
d.draw();
}
}
Output:
drawing rectangle...
drawing circle...
Explanation:
In this instance, we are examining a Drawable interface that establishes an agreement with the draw method. Following that, we introduce the Rectangle and Circle classes that adhere to this interface by furnishing their unique interpretations of the draw method. Within the main function, a Drawable type reference is employed to execute the draw method on both instances, showcasing polymorphism in action as a single interface type triggers distinct implementations.
Note: Interface methods are public and abstract by default. You cannot explicitly use public and abstract keywords for an interface method.
For Example:
using System;
public interface Drawable
{
public abstract void draw();//Compile Time Error
}
Default Interface Methods
In C# 8.0 and beyond, default interface methods allow for the direct inclusion of method implementation within an interface. This feature facilitates the addition of new members to interfaces without causing disruptions to the current classes and structs that implement them.
C# Default Interface Method Example
Let's consider a scenario to demonstrate the default interface method in C#.
Example
using System;
interface Logger
{
void Log(string message);
void LogInfo(string message)
{
Console.WriteLine($"INFO: {message}");
}
}
class ConsoleLogger : Logger
{
public void Log(string message)
{
Console.WriteLine($"LOG: {message}");
}
}
class Program
{
static void Main()
{
Logger logger = new ConsoleLogger();
logger.Log("Application started");
logger.LogInfo("Running smoothly");
}
}
Output:
LOG: Application started
INFO: Running smoothly
Explanation:
In this instance, we define an interface named Logger containing an abstract function named Log and a default function named LogInfo responsible for displaying an informational message. Following this, we introduce a class named ConsoleLogger which implements the Log function, with LogInfo utilizing the default implementation offered by the interface. Within the main routine, upon invoking a ConsoleLogger object via the Logger reference, both functions are triggered.
Interface Inheritance
In C#, interface inheritance refers to a scenario where an interface can inherit from one or more interfaces, consolidating their specifications into a single interface. Any class that implements this derived interface must provide implementations for all members defined in the inherited interfaces.
C# Interface Inheritance Example
Let's consider an example to demonstrate interface inheritance in C#.
Example
using System;
interface Movable
{
void Move();
}
interface Stoppable
{
void Stop();
}
interface Vehicle : Movable, Stoppable
{
void Start();
}
class Car : Vehicle
{
public void Move()
{
Console.WriteLine("Car is moving.");
}
public void Stop()
{
Console.WriteLine("Car has stopped.");
}
public void Start()
{
Console.WriteLine("Car has started.");
}
}
class C# Tutorial
{
static void Main()
{
Vehicle myCar = new Car();
myCar.Start();
myCar.Move();
myCar.Stop();
}
}
Output:
Car has started.
Car is moving.
Car has stopped.
Explanation:
In this instance, we showcase the concept of interface inheritance by having the Vehicle class inherit characteristics from Movable and Stoppable. Subsequently, the Car class is responsible for implementing all required methods. Within the main function, a reference to Vehicle invokes Start, Move, and Stop, showcasing the utilization of multiple interface implementations and polymorphism.
Explicit Interface Implementation in C#
In C# programming, explicit interface implementation is a method employed when a class implements multiple interfaces with methods sharing identical names. In such instances, the class must explicitly implement these interfaces to resolve any ambiguity.
C# Explicit Interface Example
Let's consider an instance to demonstrate the explicit interface in C# development.
Example
using System;
interface Employee
{
void ShowDetails();
}
interface Project
{
void ShowDetails();
}
class Employee1 : Employee, Project
{
// Explicit implementation for Employee
void Employee.ShowDetails()
{
Console.WriteLine("Employee Details: Name- Michael, ID- 101");
}
// Explicit implementation for Project
void Project.ShowDetails()
{
Console.WriteLine("Project Details: Project- C# Interfaces, Status- Completed");
}
}
class C# Tutorial
{
static void Main()
{
Employee1 emp1 = new Employee1();
// Access through Employee interface reference
Employee emp = emp1;
emp.ShowDetails();
// Access through Project interface reference
Project project = emp1;
project.ShowDetails();
}
}
Output:
Employee Details: Name- Michael, ID- 101
Project Details: Project- C# Interfaces, Status- Completed
Explanation :
In this instance, we are showcasing two Employee and Project interfaces that both have a method called ShowDetails. Within the Employee1 class, each method from the interfaces is implemented explicitly. These methods can solely be accessed via their corresponding interface references, effectively preventing any ambiguity.
When and Why Use an Interface in C#?
Interfaces in C# are an essential feature that declare contracts or specifications that classes have to comply with. We can use interfaces in the following situations:
- Defining a Common Contract: We can define an interface to establish that contract to ensure that several classes share a common group of methods, properties, events, or indexers.
- Applying Multiple Inheritance: C# does not enable multiple inheritance for classes, but enables multiple interface implementation. If we need a class to inherit behavior or structure from multiple sources, we can apply interfaces to achieve multiple inheritance. It also enables us to reuse code across different classes without any issue.
- Imposing a Specific Form: If we need to execute a specific form or a specific set of methods and properties for classes in the application or library, interfaces can be used to ensure that classes follow that form.
- Applying Polymorphism: Interfaces is an important feature to implement polymorphism in C#. When we have multiple classes implementing the same interface, we can handle objects of these classes alike, and it is simpler to work with different objects in a polymorphic manner.
Key Features of Interfaces
There are multiple characteristics of Interfaces in C#. Here are a few:
1) Contract Definition
An interface is employed to establish an agreement that the implementing class must meet by supplying implementations for all its specified members.
2) Polymorphism
In C# development, interfaces facilitate runtime polymorphism by enabling various classes to be stored as objects of a shared interface type.
3) Multiple Inheritance
The C# programming language supports multiple interface inheritance, which enables a class to implement multiple inheritances.
4) Access Modifiers
By default, all interface members are public and abstract, with no provision for private members.
5) No Fields
In the C# language, it is not possible for an interface to include instance fields, constructors, or destructors. Interfaces solely define blueprints for members.
6) Abstraction
Interface aids in achieving complete abstraction in C#. It conceals the specifics of implementation by specifying the actions a class must perform without delving into the methodology of how those actions are carried out.
Conclusion
In summary, C# interfaces offer a mechanism for specifying requirements that classes need to adhere to. They enable abstraction, multiple inheritance, and polymorphism, enhancing the adaptability, reusability, and sustainability of code. Starting from C# 8.0 onwards, interfaces have the capability to contain default methods, enhancing their effectiveness in developing extensible and organized software solutions.
C# Interface FAQs
1) What is an interface in C#?
In C#, an interface acts as an agreement that defines a set of members (such as methods, properties, events, and indexers) without any actual implementation. Any classes or structs that adhere to an interface must offer the necessary implementation for the defined members.
2) Can interfaces have constructors in C#?
No, interfaces are unable to have constructors since they are not intended for instantiation. Their purpose is to be implemented by classes or structs.
Yes, an interface can extend another interface in Java programming.
Yes, interfaces have the capability to inherit from multiple interfaces, allowing for the consolidation of multiple contracts into a single interface.
4) What sets an abstract class apart from an interface in C#?
The primary contrast between an abstract class and an interface is as outlined below:
- Abstract class: It includes variables, constructors, and a combination of method implementations.
- Interface: It is restricted from having variables or constructors, allowing only method declarations.
5) What does explicit interface implementation entail in C#?
Explicit interface implementation is a technique for defining interface methods in a way that allows them to be accessed exclusively through an interface instance, rather than directly from the class. This approach helps to prevent conflicts in method names when a class implements multiple interfaces that have the same method names.