The purpose of this tutorial is to familiarize you with the concept of interfaces in C#. You will learn how to define an interface, implement it in a class, and understand the benefits of using interfaces.
By the end of this tutorial, you'll be able to:
Prerequisites:
Basic knowledge of C# programming language.
In C#, an interface is a reference type that is similar to a class and is defined by using the interface
keyword. It is a collection of abstract methods, properties, indexers, and events.
A class or struct that implements the interface must implement all its members. It provides a contract for classes. It means a class that implements an interface must contain the methods declared in the interface.
An interface is declared using the 'interface' keyword. Here is a basic example:
public interface IVehicle
{
void Drive();
int Speed { get; set; }
}
In this case, IVehicle
is an interface that declares a method named 'Drive' and a property named 'Speed'.
A class implements an interface using the ':' operator. For example:
public class Car : IVehicle
{
private int speed;
public int Speed
{
get { return speed; }
set { speed = value; }
}
public void Drive()
{
Console.WriteLine("The car is driving.");
}
}
In the above example, Car
class is implementing the IVehicle
interface.
public interface IAnimal
{
void Speak();
}
public class Dog : IAnimal
{
public void Speak()
{
Console.WriteLine("The dog says: Woof Woof");
}
}
public class Cat : IAnimal
{
public void Speak()
{
Console.WriteLine("The cat says: Meow Meow");
}
}
class Program
{
static void Main(string[] args)
{
IAnimal myDog = new Dog();
IAnimal myCat = new Cat();
myDog.Speak();
myCat.Speak();
}
}
In this example, Dog
and Cat
classes implement the IAnimal
interface and provide their own implementations of the Speak
method. The expected output will be:
The dog says: Woof Woof
The cat says: Meow Meow
In this tutorial, we covered the definition and usage of interfaces in C#, including how to define an interface and how to implement it in a class. Interfaces are a powerful tool in C# that allow you to define contracts for classes, leading to more organized and manageable code.
To continue your learning journey, consider exploring topics such as inheritance, polymorphism, and other object-oriented programming concepts in C#.
Exercise 1: Define an interface IFlyable
with a method Fly()
. Implement this interface in two classes: Bird
and Airplane
.
Exercise 2: Define an interface IShape
with methods CalculateArea()
and CalculatePerimeter()
. Implement this interface in two classes: Rectangle
and Circle
.
Solutions to these exercises can be found in many online C# resources. Remember, the key to mastering programming is consistent practice!