C# Keywords Tutorial Part 46: interface
Amr Saafan
Founder | CTO | Software Architect & Consultant | Engineering Manager | Project Manager | Product Owner | +27K Followers | Now Hiring!
C# is an object-oriented programming language that enables the definition of interfaces to represent a group of correlated functionalities that a class must implement. Interfaces offer a means to abstract the implementation specifics of a class and outline a contract that identifies what the class is required to accomplish. In this article, we’ll examine the “interface” keyword in C# using code examples.
Defining an Interface
An interface is defined using the “interface” keyword in C#. Let’s define an example interface for a calculator:
public interface ICalculator
{
? ? int Add(int x, int y);
? ? int Subtract(int x, int y);
? ? int Multiply(int x, int y);
? ? int Divide(int x, int y);
}
This interface defines four methods for performing basic arithmetic operations. The methods do not have any implementation details, but they specify what a class that implements the interface should be able to do.
Implementing an Interface
To implement an interface, a class must use the “implements” keyword and provide implementations for all the methods in the interface. Let’s define a class called “BasicCalculator” that implements the ICalculator interface:
领英推荐
public class BasicCalculator : ICalculator
{
? ? public int Add(int x, int y)
? ? {
? ? ? ? return x + y;
? ? }
? ? public int Subtract(int x, int y)
? ? {
? ? ? ? return x - y;
? ? }
? ? public int Multiply(int x, int y)
? ? {
? ? ? ? return x * y;
? ? }
? ? public int Divide(int x, int y)
? ? {
? ? ? ? return x / y;
? ? }
}
The BasicCalculator class provides implementations for all the methods in the ICalculator interface. Now, any code that expects an ICalculator object can use a BasicCalculator object instead.
Using an Interface
Interfaces are useful because they allow you to write code that works with any object that implements the interface, without knowing the specific implementation details. Let’s see an example of how to use the ICalculator interface in C#:
public static void Calculate(ICalculator calculator)
{
? ? int result = calculator.Add(5, 10);
? ? Console.WriteLine($"Result of 5 + 10 is: {result}");
? ? result = calculator.Multiply(2, 3);
? ? Console.WriteLine($"Result of 2 * 3 is: {result}");
}
static void Main(string[] args)
{
? ? ICalculator calculator = new BasicCalculator();
? ? Calculate(calculator);
}
The Calculate method takes an ICalculator object as a parameter and performs some arithmetic operations using it. In the Main method, we create a BasicCalculator object and pass it to the Calculate method. Since BasicCalculator implements the ICalculator interface, it can be used wherever an ICalculator object is expected.