Interfaces in C#
An interface in C# is a blueprint or contract that defines a set of methods, properties, events, or indexers that a class or struct must implement. It only specifies the names and signatures of members without providing any actual code or implementation for them. When a class implements an interface, it agrees to provide the specific implementation for all its defined members.
It is used to achieve multiple inheritance which can’t be achieved by class. It is used to achieve full abstraction because it cannot have a method body.
Basic Structure :
public interface IMyInterface
{
// Declare methods (no implementation)
void Methodname();
}
Interface Declaration:
- Interfaces are declared using the interface keyword followed by the interface name (IMyInterface in this example).
- By convention, interface names in C# typically start with an uppercase “I”.
Scenario: Payment Processing System
You are developing a payment processing system for an e-commerce platform. The system must support different payment methods, such as Credit Card, PayPal, and Bank Transfer. In the future, new payment methods might be added (like Bitcoin or Apple Pay). To make the system flexible and extendable, you can use an interface that defines the contract for any payment method.
using System;
public interface IPayment
{
void ProcessPayment(decimal amount);
}
public interface ILogging
{
void LogPayment(string message);
}
public class CreditCard : IPayment, ILogging
{
public void ProcessPayment(decimal amount)
{
Console.WriteLine($”Processing Credit Card payment of {amount} dollars.”);
}
public void LogPayment(string message)
{
Console.WriteLine($”CreditCard Log: {message}”);
}
}
public class PayPal : IPayment, ILogging
{
public void ProcessPayment(decimal amount)
{
Console.WriteLine($”Processing PayPal payment of {amount} dollars.”);
}
public void LogPayment(string message)
{
Console.WriteLine($”PayPal Log: {message}”);
}
}
class Program
{
static void Main()
{
CreditCard creditCardPayment = new CreditCard();
creditCardPayment.ProcessPayment(150.00m);
creditCardPayment.LogPayment(“Credit Card payment of 150 dollars was successful.”);
PayPal payPalPayment = new PayPal();
payPalPayment.ProcessPayment(200.50m);
payPalPayment.LogPayment(“PayPal payment of 200.50 dollars was successful.”);
}
}
Explanation:
using System;
Define the IPayment interface for different payment methods
public interface IPayment
{
void ProcessPayment(decimal amount); // Contract for processing payments
}
Define the ILogging interface for logging payment details
public interface ILogging
{
void LogPayment(string message); // Contract for logging payment actions
}
CreditCard class that implements both IPayment and ILogging interfaces
public class CreditCard : IPayment, ILogging
{
public void ProcessPayment(decimal amount)
{
Console.WriteLine($”Processing Credit Card payment of {amount} dollars.”);
}
public void LogPayment(string message)
{
Console.WriteLine($”CreditCard Log: {message}”);
}
}
PayPal class that implements both IPayment and ILogging interfaces
public class PayPal : IPayment, ILogging
{
public void ProcessPayment(decimal amount)
{
Console.WriteLine($”Processing PayPal payment of {amount} dollars.”);
}
public void LogPayment(string message)
{
Console.WriteLine($”PayPal Log: {message}”);
}
}
Main program to demonstrate payment and logging with multiple interfaces
class Program
{
static void Main()
{
// Process and log payment using Credit Card
CreditCard creditCardPayment = new CreditCard();
creditCardPayment.ProcessPayment(150.00m); // Processing Credit Card payment
creditCardPayment.LogPayment(“Credit Card payment of 150 dollars was successful.”); // Logging
// Process and log payment using PayPal
PayPal payPalPayment = new PayPal();
payPalPayment.ProcessPayment(200.50m); // Processing PayPal payment
payPalPayment.LogPayment(“PayPal payment of 200.50 dollars was successful.”); // Logging
}
}
Course Video:
Course Video English:
Task:
1. Basic Interface Implementation:
Create an interface IAnimal with a method Speak. Implement this interface in two classes Dog and Cat with their respective implementations of Speak method. In the Main method, create instances of Dog and Cat and call their Speak methods.
2. Interface with Properties and Methods:
Define an interface IVehicle with a property Speed and a method Drive. Implement this interface in two classes Car and Bike. Set the speed and implement the Drive method to print a message indicating the vehicle’s speed. In the Main method, create instances of Car and Bike, set their speeds, and call the Drive method.
3. Interface Inheritance:
Create an interface IShape with methods CalculateArea and CalculatePerimeter. Create another interface IColoredShape that inherits from IShape and adds a property Color. Implement IColoredShape in a class Rectangle. In the Main method, create an instance of Rectangle, set its properties, and call its methods.
.
4. Interface and Abstract Class Combination:
Create an interface IRunnable with a method Run and an abstract class Machine with an abstract method Start. Create a class Robot that inherits from Machine and implements IRunnable. Provide implementations for the Start and Run methods. In the Main method, create an instance of Robot, and call its methods.
An interface in C# defines a contract that other classes or structs must follow. It contains declarations for methods, properties, events, or indexers, without implementation.
Use the interface keyword, e.g., interface IExample.
No, interfaces cannot contain fields. They can only have method declarations, properties, events, or indexers.
- Interface: Cannot have any implementation; multiple inheritance is allowed.
- Abstract Class: Can have partial implementation; only single inheritance is allowed.
Yes, a class can implement multiple interfaces, enabling multiple inheritance behavior.
Interfaces provide a way to achieve polymorphism and decouple code by defining contracts that multiple classes can implement.
Yes, interfaces can inherit from one or more other interfaces.
The class must be declared as abstract if it does not implement all interface members.
Explicit implementation allows a class to implement interface members so that they are not accessible through the class instance, only through an interface reference.
Starting with C# 8.0, interfaces can have default implementations for members, which provide a basic implementation that classes can override.
Iqra Technology Academy offers free video tutorials in Hindi that explain interfaces in C# with properties. These tutorials cover the basics of interfaces, how they work, and how to use them with properties in C# with practical examples.
In C#, properties in interfaces allow classes to define getters and setters for specific data. The interface specifies the signature for the property, but the class that implements the interface provides the actual implementation for the property.
Example:
interface IEmployee
{
string Name { get; set; }
double Salary { get; set; }
}
class Employee : IEmployee
{
public string Name { get; set; }
public double Salary { get; set; }
}
Here, the IEmployee interface defines Name and Salary properties, and the Employee class implements them.
Using interfaces with properties in C# allows you to define a common contract for different classes. This ensures that all implementing classes will have specific properties, making the code more flexible, reusable, and maintainable. It also helps in achieving polymorphism and abstraction.