Welcome to The Coding College! In this tutorial, we’ll explore Interfaces in C#, an essential part of Object-Oriented Programming (OOP). Interfaces are a key feature in C# that allow you to define contracts for classes and ensure they implement specific methods.
What is an Interface in C#?
An interface in C# is like a blueprint for a class. It defines a contract that a class must fulfill. Unlike classes, interfaces do not provide implementations for their methods; they only specify method signatures.
Key Points:
- Interfaces cannot contain any fields, constructors, or method implementations.
- A class or struct that implements an interface must provide implementations for all its members.
- C# supports multiple inheritance for interfaces, meaning a class can implement multiple interfaces.
Syntax for an Interface
interface IInterfaceName
{
// Method signature
void MethodName();
// Property signature
int PropertyName { get; set; }
}
How to Implement an Interface
A class implements an interface using the :
symbol. The class must then provide concrete definitions for all the methods and properties in the interface.
Example:
using System;
interface IVehicle
{
void Drive();
void Stop();
}
class Car : IVehicle
{
public void Drive()
{
Console.WriteLine("The car is driving.");
}
public void Stop()
{
Console.WriteLine("The car has stopped.");
}
}
class Program
{
static void Main()
{
IVehicle myCar = new Car();
myCar.Drive();
myCar.Stop();
}
}
Output:
The car is driving.
The car has stopped.
Properties in Interfaces
Interfaces can define property signatures, and the implementing class must include these properties with get
and set
accessors.
Example:
using System;
interface IPerson
{
string Name { get; set; }
int Age { get; set; }
void DisplayInfo();
}
class Student : IPerson
{
public string Name { get; set; }
public int Age { get; set; }
public void DisplayInfo()
{
Console.WriteLine($"Name: {Name}, Age: {Age}");
}
}
class Program
{
static void Main()
{
IPerson student = new Student { Name = "Alice", Age = 20 };
student.DisplayInfo();
}
}
Output:
Name: Alice, Age: 20
Multiple Interfaces
C# allows a class to implement multiple interfaces. This feature is useful when you want a class to fulfill multiple roles.
Example:
using System;
interface IAnimal
{
void Eat();
}
interface IPet
{
void Play();
}
class Dog : IAnimal, IPet
{
public void Eat()
{
Console.WriteLine("The dog is eating.");
}
public void Play()
{
Console.WriteLine("The dog is playing.");
}
}
class Program
{
static void Main()
{
Dog myDog = new Dog();
myDog.Eat();
myDog.Play();
}
}
Output:
The dog is eating.
The dog is playing.
Default Interface Methods (C# 8.0 and Later)
Starting with C# 8.0, interfaces can include default implementations for methods. This allows you to add new methods to an existing interface without breaking existing implementations.
Example:
interface IGreeting
{
void SayHello();
// Default implementation
void SayGoodbye()
{
Console.WriteLine("Goodbye!");
}
}
class Person : IGreeting
{
public void SayHello()
{
Console.WriteLine("Hello!");
}
}
class Program
{
static void Main()
{
IGreeting person = new Person();
person.SayHello();
person.SayGoodbye();
}
}
Output:
Hello!
Goodbye!
Interfaces vs Abstract Classes
Feature | Interface | Abstract Class |
---|---|---|
Implementation | Cannot have implementation (except defaults). | Can have both implemented and abstract methods. |
Inheritance | Supports multiple inheritance. | Supports single inheritance only. |
Constructors | Cannot have constructors. | Can have constructors. |
Access Modifiers | All members are implicitly public. | Members can have any access modifier. |
When to Use Interfaces
- Defining Contracts: Use interfaces to specify a contract for classes without dictating how they should implement it.
- Multiple Roles: Use interfaces when a class needs to implement multiple functionalities.
- Loosely Coupled Design: Interfaces allow components to interact without being tightly bound to specific implementations.
Advantages of Interfaces
- Flexibility: A single class can implement multiple interfaces.
- Scalability: Interfaces make it easy to add new functionality.
- Testability: Interfaces enable mocking and easier unit testing.
- Separation of Concerns: They define “what to do” without specifying “how to do it.”
Best Practices
- Use meaningful names for interfaces, typically starting with an I (e.g.,
IVehicle
). - Keep interfaces small and focused on a single responsibility.
- Favor interfaces over concrete classes in method signatures to promote loose coupling.
Conclusion
Interfaces are a powerful tool in C# that enhance code flexibility, scalability, and maintainability. By defining clear contracts for your classes, interfaces allow you to build robust and modular applications.
Explore more C# tutorials and deepen your programming knowledge at The Coding College. Happy coding! 🎉