How to Implement Interface in C#
What is an Interface?
A programming structure or syntax known as an interface enables the computer to -impose characteristics on an object (class). Let's take an example where we have classes for cars, scooters, and trucks. There should be a start_engine() action for each of these three classes. The domain of the interface is the requirement that each vehicle has a start_engine action; how each vehicle's "engine is started" is left to that specific class.
A contract exists between an interface and any class that implements it. An interface may contain events, attributes, or methods. It merely includes a declaration of its members; the class that implements the interface will provide the implementation of its members. Program maintenance is made simple by the interface. The interface's defined terms are listed below.
An interface can have members like as methods, properties, events, and indexers, much like a class. However, interfaces will only include the members' declarations. The class that implements the interface either explicitly or indirectly will be responsible for providing the members' implementation.
- The interface keyword can be used to specify an interface.
- Private members are not allowed on interfaces.
- All interface members are publicly accessible by default.
- Interfaces impose requirements on classes to implement their members.
- Members of an interface are public and abstract by default.
- Fields and constructors are not permitted in an interface.
There are two methods by which we can implement the interface, as follows:
1. Implicit
2. Explicit
Interface in C#:
The interface keyword in C# can be used to define an interface. Declarations of methods, properties, indexers, and events are all possible in an interface. It is unable to include instance fields, though.
Members of the interface are not subject to access modifiers. Starting with C #8.0, you can utilize virtual, abstract, sealed, static, extern, partial, private, protected, internal, and public modifiers under specific circumstances.
Syntax for Interface:
Declaration:
interface Interface_name
{
// declare methods
//Declare properties
}
Implementation:
Class name: Interface_name
{
//code
}
Example for declaring interface in C#:
interface IExample
{
void Greetings();
void Welcome(string text);
}
The interface IExample is declared in the above. (It is advised to begin an interface name with the letter "I" so that it is immediately apparent that this is an interface and not a class: Greetings() and Welcome(string) are the two methods available in the IExample interface.
Implementing Interface in C# using the class:
A class or a structure can implement one or more interfaces using a colon: When you deploy an interface, you must control its members.
Syntax:
class Class_name : Interface_name
{
//methods and properties
}
Example:
public interface IShape
{
double CalculateArea();
}
public class Circle : IShape
{
public double Radius { get; set; }
public Circle(double radius)
{
Radius = radius;
}
public double CalculateArea()
{
return Math.PI * Radius * Radius;
}
}
public class Rectangle : IShape
{
public double Width { get; set; }
public double Height { get; set; }
public Rectangle(double width, double height)
{
Width = width;
Height = height;
}
public double CalculateArea()
{
return Width * Height;
}
}
class Program
{
static void Main(string[] args)
{
Circle circle = new Circle(5);
Console.WriteLine("Area of Circle: " + circle.CalculateArea());
Rectangle rectangle = new Rectangle(4, 6);
Console.WriteLine("Area of Rectangle: " + rectangle.CalculateArea());
}
}
Output:
![How to Implement Interface in C#](https://static.tutorialandexample.com/csharp/how-to-implement-interface-in-csharp1.png)
Classes can implement an interface's members to abide by the contract defined by the interface in C#. To calculate the area of different geometric forms, for example, consider an interface called IShape that has a method called CalculateArea(). It is required of classes that implement IShape to supply their own CalculateArea() implementation.
The classes Circle and Rectangle in our example implement IShape. Every class has unique logic for computing the area using the formula for that shape. Polymorphism, which allows treating objects of different classes implementing the same interface interchangeably, is the benefit of using interfaces.
We first build instances of the Circle and Rectangle classes in the Main method and then call their CalculateArea() functions. They are called with the same interface reference even though they have separate implementations. This flexibility enables cleaner code because it simplifies maintenance, encourages code reuse, and makes testing easier. Furthermore, by allowing classes to rely on abstractions rather than specific implementations, interfaces encourage loose coupling and improve the scalability and extensibility of big software systems.
Explicit Implementation:
<InterfaceName>.<MemberName> can be used to implement an interface explicitly. When a class implements more than one interface, explicit implementation helps to make it easier to read and clear up any confusion. Coincidentally, it is also helpful if interfaces have the same method name.
Example Code:
using System;
public interface IMyInterface
{
void MyMethod();
string MyProperty { get; set; }
}
public class MyClass : IMyInterface
{
private string _myProperty;
void IMyInterface.MyMethod()
{
Console.WriteLine("Explicit implementation");
}
public string MyProperty
{
get
{
return _myProperty;
}
set
{
_myProperty = value;
}
}
}
class Program
{
static void Main()
{
MyClass myClass = new MyClass();
((IMyInterface)myClass).MyMethod();
myClass.MyProperty = "Hello, all!";
Console.WriteLine(myClass.MyProperty);
}
}
Output:
![How to Implement Interface in C#](https://static.tutorialandexample.com/csharp/how-to-implement-interface-in-csharp2.png)
With a method called MyMethod and a property called MyProperty, the code defines an interface called IMyInterface. This interface is implemented by the class MyClass. MyMethod can be accessed by casting an instance of MyClass to IMyInterface since it is implemented using explicit interface implementation. By using MyClass instances, this technique conceals the method from direct access. In addition to being expressly implemented, MyProperty also has public accessors that enable direct access to the value kept in the private field _myProperty. An instance of MyClass is created in the Main method, and MyMethod is called after casting. The value of MyProperty is then printed once it has been set to "Hello, World!" By resolving naming conflicts and guaranteeing encapsulation, explicit implementation directs users to access interface members based on the interface type.
Multiple Interfaces Implementation:
Multiple interfaces can be implemented by a class or struct. It needs to offer every interface member's implementation.
using System;
public interface IShape
{
double Area();
}
public interface IDrawable
{
void Draw();
}
public class Circle : IShape, IDrawable
{
private double _radius;
public Circle(double radius)
{
_radius = radius;
}
public double Area()
{
return Math.PI * _radius * _radius;
}
public void Draw()
{
Console.WriteLine($"Drawing a circle with radius {_radius}");
}
}
class Program
{
static void Main()
{
Circle circle = new Circle(5.0);
Console.WriteLine($"Area of the circle: {circle.Area()}");
circle.Draw();
}
}
Output:
![How to Implement Interface in C#](https://static.tutorialandexample.com/csharp/how-to-implement-interface-in-csharp3.png)
Two interfaces, IShape and IDrawable, are implemented by the class Circle, as the code illustrates. The Area method, which determines a circle's area from its radius, must be used in order to use the IShape interface. The Draw function, which is in charge of informing the user that a circle with a given radius is being drawn, must be implemented in order to use the IDrawable interface.
The circle's radius is represented in the Circle class by the _radius field. The Area technique calculates the area using the formula Math: _ radius* PI* _ radius. The Draw method outputs a message using the Console.WriteLine with the radius value included.
A Circle instance with a radius of 5.0 is created in the Main function. In this instance, the area of the circle is calculated and shown by invoking the Area method. The drawing of the circle with its radius is then graphically shown by calling the Draw function.
Thus, the Circle class acquires the capability to calculate its area and display a visual representation by implementing both the IShape and IDrawable interfaces, demonstrating the flexibility of multiple interface implementation in C#.
Default Interface Methods:
using System;
interface IFile
{
void ReadFile();
void WriteFile(string text);
void DisplayName()
{
Console.WriteLine("IFile");
}
}
class FileInfo : IFile
{
public void ReadFile()
{
Console.WriteLine("Reading File");
}
public void WriteFile(string text)
{
Console.WriteLine("Writing to file");
}
}
public class Program
{
public static void Main()
{
IFile file1 = new FileInfo();
file1.ReadFile();
file1.WriteFile("content");
file1.DisplayName();
FileInfo file2 = new FileInfo();
}
}
Output:
![How to Implement Interface in C#](https://static.tutorialandexample.com/csharp/how-to-implement-interface-in-csharp4.png)
The code defines the IFile interface, which has three members: the default DisplayName method that prints "IFile" to the console, ReadFile, and WriteFile. The FileInfo class, which implements IFile, provides concrete implementations of ReadFile and WriteFile.
A FileInfo instance called file1 is assigned to IFile in Main. This demonstrates the versatility of the interface by enabling direct calls to the default DisplayName method, ReadFile, and WriteFile. On the other hand, because of its type, file2, which is likewise an instance of FileInfo, is unable to invoke the default DisplayName function directly. This demonstrates how alternative method accessibility can be provided via interfaces based on the kind of object.
In essence, the code highlights the variety and polymorphism possible with C# interface implementation by showing how interfaces can have default implementations and how objects of various kinds can interact with interface members.the digital gap and connect residents of underprivileged areas to the internet.