C# Interface

  Mastering C# Interface: Step-by-Step Tutorial with Hands-on Code Samples

Welcome to our comprehensive tutorial on mastering C# interfaces! Whether you’re a beginner or an experienced developer, understanding and leveraging interfaces is crucial for writing clean and maintainable code. In this step-by-step guide, we’ll demystify the concept of interfaces with hands-on code samples that will solidify your knowledge and empower you to incorporate them seamlessly into your projects. Get ready to unlock a new level of programming proficiency as we journey through the world of C# interfaces together!

  Need a Password Manager?

  Introduction to C# Interface

Introduction to C# Interface:

C# interface is an integral part of object-oriented programming (OOP) and it allows developers to create a contract or set of rules that a class must follow. It acts as a blueprint for the behavior of an object, without actually implementing the methods itself. Interfaces in C# provide a way for unrelated classes to indirectly work together, promoting loose coupling and increasing code reusability.

In simpler terms, an interface is like a template that defines what functions and properties an implementing class should have. It contains only the method signatures and properties without any implementation details, making it different from abstract classes which can have both implemented and non-implemented members.

The concept of interfaces is not unique to C#, as it has been adopted by multiple languages including Java, C++, and PHP. However, C# interfaces have some extra features such as support for events and default implementations starting with C# 8.0.

Why Use Interfaces in C#:

Interfaces play a vital role in achieving one of the key principles of OOP – abstraction. By separating the declaration from the implementation, interfaces allow developers to focus on creating modular components that can be easily maintained and extended.

Another benefit of using interfaces is that they enable polymorphism, meaning multiple classes can inherit from a single interface while still implementing their own unique functionality. This ensures code flexibility and helps avoid tight coupling between classes.

  – Definition of Interface in C#

The concept of interfaces in C# can be a bit confusing for beginners, but mastering them is crucial for becoming a proficient C# programmer. In this section, we will discuss the definition of interfaces in C#, their role in object-oriented programming, and how to use them effectively.

As the name suggests, an interface acts as an intermediate or “interface” between two entities. In the context of C#, an interface serves as a contract that defines a set of methods, properties, events, or indexers that must be implemented by any class that wants to use it. It specifies what actions can be performed on an object without revealing how those actions are implemented.

In simpler terms, an interface is like a blueprint outlining what functionalities an object should have. However, it does not provide any implementation details; instead, it delegates these responsibilities to classes that implement it. This feature makes interfaces one of the fundamental building blocks of C# programming language.

Interfaces play a vital role in achieving code reusability and maintainability in object-oriented programming. By defining common behaviors through interfaces, multiple classes can implement them without duplicating code and achieve consistency in implementing those behaviors across different objects.

Now let’s take a closer look at the syntax used for creating interfaces in C#. Interfaces are declared using the `interface` keyword followed by the name of the interface. Inside curly braces `{}`, we define its members. Let’s consider a simple example:

public interface ICalculator
{
  int Add(int num1 , int num2);
  int Subtract(int num1, int num2);
}
  

In this example, we have defined an interface named `ICalculator` with two methods: `Add` and `Subtract`, which take two integer parameters and return an integer value. Notice that these methods are declared without any implementation details; they only specify the method signature. Any class that implements this interface must provide its own implementation for these methods.

Now let’s see how to use this interface in a class:

public class BasicCalculator : ICalculator
{
  public int Add(int num1, int num2)
  {
    return num1 + num2;
  }

  public int Subtract(int num1, int num2)
  {
    return num1 - num2;
  }
}

Here, our `BasicCalculator` class implements the `ICalculator` interface by providing its own implementation for the `Add` and `Subtract` methods. This allows us to use objects of the `BasicCalculator` class wherever an object of type `ICalculator` is expected.

To summarize, interfaces in C# are used to define common behaviors or functionalities that can be implemented by multiple classes. They act as a contract between different entities, promoting code reusability and maintainability. As you continue your journey in C# programming, make sure to practice creating and implementing interfaces to become comfortable with this crucial concept.

  – Importance of Interfaces in Object-Oriented Programming

Object-oriented programming (OOP) is a popular programming paradigm that focuses on creating software using objects and their interactions. One of the key elements of OOP is interfaces, which define a set of behaviors or functionalities that an object must implement. In this section, we will delve deeper into the importance of interfaces in object-oriented programming and why mastering them is crucial for every C# developer.

1) Encapsulation:
The first and foremost reason for the importance of interfaces in OOP is encapsulation. Interfaces allow us to separate the implementation details from the interface definition, providing a level of abstraction that allows us to change the implementation without affecting the rest of our code. This makes our code more maintainable and extensible, as we can easily add new implementations without breaking existing functionality.

2) Modularity:
Interfaces also promote modularity in our code by allowing us to break down complex systems into smaller, more manageable parts. By defining interfaces, we can create independent modules that can communicate with each other through well-defined contracts. This promotes code reusability and helps developers work on different parts of a system simultaneously without worrying about dependencies.

3) Polymorphism:
Another essential aspect of OOP is polymorphism, which allows objects to have different forms or behaviors based on their type. Interfaces play a significant role in achieving polymorphism by allowing multiple classes to implement the same interface but provide their own unique implementation for its methods. This not only promotes code reuse but also adds flexibility to our codebase.

4 ) Design Patterns:
Many design patterns in OOP rely heavily on interfaces, such as the Factory Method, Adapter, and Observer patterns. These patterns allow us to write efficient and maintainable code by providing a standard way of solving common programming problems. Mastering interfaces is crucial for understanding and implementing these patterns correctly.

5) Testing:
Interfaces also make testing easier by allowing us to mock or stub objects during unit testing. By creating interfaces for dependencies, we can easily replace them with mock implementations for testing purposes. This enables us to test our code in isolation without relying on external resources, speeding up the development process and improving overall code quality.

6) Dependency Injection:
Dependency injection (DI) is another important concept in OOP that relies heavily on interfaces. DI is a technique where an object’s dependencies are passed in through its constructor or setter methods instead of being directly instantiated within the class. Interfaces are used to define these dependencies, making it easier to swap them out with different implementations at runtime.

7) Frameworks and Libraries:
Many frameworks and libraries in C# use interfaces extensively, making it essential for developers to understand how they work. For example, ASP.NET Core uses dependency injection through interfaces to manage application dependencies and promote loose coupling between components. Understanding interfaces is crucial for working with such frameworks and libraries effectively.

In conclusion, interfaces play a crucial role in object-oriented programming by promoting encapsulation, modularity, polymorphism, and other important principles. Mastering interfaces allows developers to write well-structured code that is easier to maintain, test, and extend. Therefore, it is important for every C# developer to have a good understanding of interfaces to become proficient in OOP.

  Basics of Implementing an Interface

Implementing an interface is a fundamental concept in C# programming. It allows classes to inherit behaviors and functionality from one or multiple interfaces, making code more flexible and reusable. In this section, we will delve into the basics of implementing an interface in C#, covering everything you need to know to master this powerful tool.

1. Understanding Interfaces

Before diving into implementation, it’s crucial to understand what interfaces are and why they are used in C#. An interface is a blueprint for a group of related operations or functionalities that can be implemented by different classes. It defines only the method signatures without any implementation details, forcing classes that implement it to provide their own custom logic for those methods.

2. Declaring an Interface

To declare an interface in C#, you use the `interface` keyword followed by the name of the interface and its members enclosed within curly braces. Let’s look at an example of an `IVehicle` interface:

public interface IVehicle
{
  void StartEngine();
  void StopEngine();
  int GetFuelLevel();
}

As you can see, the above declaration doesn’t contain any actual code; it merely outlines what the class implementing this interface should do.

3. Implementing an Interface

To implement an interface, you use the `class` keyword followed by the name of your class, then specify which interfaces it will implement using a colon (`:`) symbol before its body. Once your class implements an interface, it must implement all its defined members . Let’s look at an example of a `Car` class that implements the `IVehicle` interface:

public class Car : IVehicle
{
  private int fuelLevel = 0;
  public void StartEngine()
  {
    // logic to start the car engine
  }

  public void StopEngine()
  {
    // logic to stop the car engine
  }

  public int GetFuelLevel()
  {
    return fuelLevel;
  }
}

In the example above, we have a `Car` class that implements the `StartEngine()`, `StopEngine()`, and `GetFuelLevel()` methods defined in the `IVehicle` interface. Notice how each method includes its own custom logic, as required by the interface contract.

4. Accessing Interface Members

Once you have implemented an interface, you can access its members (methods) through an object instance of your implementing class. Let’s create an instance of our `Car` class and call its methods through the interface:

// create a new instance of Car
var myCar = new Car();

// call methods through interface reference
IVehicle vehicle = myCar;
vehicle.StartEngine();
vehicle.StopEngine();

// or directly from the car instance
myCar.StartEngine();
myCar.StopEngine();

As you can see, we can call the same methods either through an interface reference or directly from the class instance.

5. Implementing Multiple Interfaces

One of the significant advantages of interfaces is that a class can implement multiple interfaces simultaneously. To do this, simply separate each interface name with a comma (`,`) when declaring your class:

public class Truck : IVehicle, IHeavyVehicle
{
  // code for implementing both interfaces
}

6. Explicit Interface Implementation

In some cases, you may have two interfaces with the same method name but different functionality. In such situations, you can explicitly specify which interface’s method should be invoked by using the syntax `interfaceName.methodName()`. Let’s look at an example:

public interface IDrivable
{
  void Drive();
}

public interface IFlyable
{
  void Drive();
}

public class HybridVehicle : IDrivable, IFlyable
{
  public void Drive()
  {
    // default implementation 
    Console.WriteLine("Default drive function");
  }

  void IDrivable.Drive()
  {
    // specific Drive implementation for drivable vehicle 
    Console.WriteLine(" Driving on the ground");
  }

  void IFlyable.Drive()
  {
    // specific Drive implementation for flyable vehicle 
    Console.WriteLine("Flying through the air");
  }
}

In the example above, we have two interfaces; `IDrivable` and `IFlyable`, each with a `Drive()` method. The `HybridVehicle` class implements both interfaces and provides its own custom implementation for the method. However, in this case, we need to specify which interface’s implementation of `Drive()` we want to invoke.

7. Using Interfaces in Collections

Another useful feature of interfaces is that they can be used as types in collections. This means you can create a collection that contains objects of different classes that implement the same interface. Let’s look at an example:

// create an array that holds vehicles
IVehicle[] vehicles = new IVehicle[2];
vehicles[0] = new Car();
vehicles[1] = new Truck();

// loop through and call common methods
foreach (var vehicle in vehicles)
{
  vehicle.StartEngine();
  vehicle.StopEngine();
}

Here, we have created an array of type `IVehicle` that can hold both a `Car` and `Truck` object, which are two unrelated classes. This allows us to call common methods on the objects without worrying about their specific type.

8. Best Practices for Implementing Interfaces

– Use interfaces to define a contract for a group of related operations or functionalities.
– Name your interfaces with an `I` prefix to clearly differentiate them from classes.
– Keep interface declarations small and focused on a single purpose, enforcing low coupling and high cohesion.
– Avoid including unnecessary implementation details or fields in an interface; this is what classes are for.
– Always implement all members defined in an interface when implementing it in a class.
– Use explicit interface implementation if you want to provide different functionality for the same method name in different interfaces.
– Utilize interfaces as types in collections to increase flexibility and maintainability of code.

  – Steps for Creating an Interface in C#

Creating interfaces in C# is an essential skill for any programmer looking to master the language. Interfaces allow for the implementation of polymorphism and abstraction, making code more flexible and maintainable. In this section, we will guide you through the steps of creating an interface in C# with detailed explanations and hands-on code samples.

1. Define your interface
To create an interface in C#, start by defining it using the ‘interface’ keyword followed by a name that represents its purpose or functionality. The interface name should be meaningful and follow standard naming conventions, such as using PascalCase for multi-word names.

Example:

public interface ILogger
{
  // Interface members will go here
}

2. Declare Interface Members
Next, declare the members of your interface within curly braces `{}`. These members can include properties, methods, events, or indexers without implementing their functionality since an interface cannot contain any implementation details.

Example:

public void Log(string message);
public int GetCount();

3. Implementing Interfaces
Interfaces are implemented by classes using the `:` symbol after a class’s declaration, followed by the name/s of all interfaces it is going to implement.

Example:

class ConsoleLogger : ILogger // Class implementing ILogger interface
{
  // Implementation details for ILogger members go here
}

class FileLogger : ILogger // A different class also implementing ILogger
{
  // Implementation details for ILogger members go here
}

4. Interface Inheritance
Just like classes, interfaces can also inherit from other interfaces using the `:` symbol.

Example:

public interface IFileLogger : ILogger
{
  void ReadLogFile();
}

5. Using Interfaces in Code
To use an interface, create an instance of a class that implements the interface and assign it to an interface variable. This variable can then access all the members declared in the interface using dot notation.

Example:

ILogger logger = new ConsoleLogger(); // creating an instance of ConsoleLogger class

logger.Log("This is a log message"); // Accessing Log method through Interface variable
int count = logger.GetCount(); // Accessing GetCount method through Interface variable

6. Explicit Interface Implementation
In some cases, you may want a class to implement multiple interfaces with members having identical names. In such situations, C# allows you to explicitly implement these interfaces to avoid conflicts by using the fully qualified interface name before a method or property declaration.

Example:

interface ILog1 {
  void DoSomething();
}

interface ILog2 {
  void DoSomething();
}

class FileLogger : ILog1, ILog2 {

  void ILog1.DoSomething() {
    // Declaration of first method for ILog1
  }

  void ILog2.DoSomething() {
    // Declaration of second method for ILog2
  }
}

7. Using Interfaces as Type Parameters
Interfaces can also be used as type parameters in generic classes, which allows you to use different implementations of the interface with the same generic class.

Example:

public class LoggerManager where T : ILogger
{
  // Code logic using methods from ILogger Interface

  private T logger;
  public LoggerManager(T log)
  {
    this.logger = log;
  }
}

8. Common Mistakes to Avoid While Creating an Interface
– Forgetting to declare interface members within curly braces `{}`.
– Attempting to call an interface member from a class that does not implement it.
– Declaring interface members with access modifiers like `public` or `private`. All Interface members are implicitly public.
– Re-declaring interface members when inheriting another interface.

Congratulations, you now know how to create interfaces in C#! Remember, interfaces are critical tools for achieving polymorphism and abstraction, so make sure you understand their purpose and use them effectively in your code.

  – How Interfaces differ from Classes

Interfaces and classes are fundamental concepts in object-oriented programming (OOP). They both play a crucial role in defining the structure of an application and how it interacts with other components. However, there are significant differences between interfaces and classes that developers must understand to effectively use them in their projects.

1. Definition
The most notable difference between interfaces and classes is their definition. A class is a blueprint for creating objects, while an interface is a contract that defines the capabilities or behaviors that a class must implement. In simpler terms, a class provides the implementation details for objects, whereas an interface only outlines what those implementations should look like.

2. Implementation vs Abstraction
Classes provide concrete implementations of methods and properties, making them an essential part of building functional applications. Interfaces, on the other hand, only contain abstract methods and properties without any implementation details. This makes them purely abstract entities that represent concepts rather than actual code.

3. Inheritance
Inheritance refers to the ability of one class to inherit the characteristics (methods and properties) of another class. In C#, this can be achieved through single or multiple inheritance using the “extends” keyword. Classes can inherit from another class, but they cannot inherit from an interface since interfaces do not have any concrete implementations.

4. Multiple Implementations
A key advantage of interfaces over classes is that a single class can implement multiple interfaces simultaneously, allowing it to take on different behaviors depending on which interface it implements. This feature enables developers to create flexible and modular code that can adapt to different scenarios.

5. Constructor
Classes have constructors, which are used to initialize objects when they are created. Interfaces, on the other hand, cannot have constructors because they do not represent actual objects. Instead, they only define a set of rules for classes to follow.

6. Access Modifiers
In C#, access modifiers such as public, private, and protected can be applied to class members to control their visibility and accessibility. However, interfaces can only have public members since their sole purpose is to be implemented by classes.

7. State
Classes can have state in the form of fields (variables) that hold data related to the object’s behavior and properties (getters/setters) that allow accessing and modifying this data. Interfaces, on the other hand, do not have any state; they only specify what functionalities a class should provide.

  – Syntax and Structure of Interfaces

The syntax and structure of interfaces is a crucial aspect of mastering C# interface. Interfaces in C# are similar to classes in many ways, but they have some distinct differences that make them stand out. In this section, we will delve deeper into the syntax and structure of interfaces to gain a better understanding of how they work.

Syntax:

To declare an interface in C#, we use the ‘interface’ keyword followed by the name of the interface. For example,

public interface IAnimal
{
  void Move();
}

The above code snippet declares an interface named `IAnimal` with a single method `Move()`. The methods declared inside an interface do not have any implementation; they only contain method signatures.

It is worth noting that all methods and properties inside an interface are implicitly public and abstract, meaning they do not have a definition and must be implemented by any class that implements the interface.

To implement an interface, we use the ‘:’ symbol after the class name followed by the name of the interface being implemented. For example,

public class Dog : IAnimal
{
  public void Move()
  {
    Console.WriteLine("Running on four legs");
  }
}

Above, we have created a class called `Dog` that implements the `IAnimal` interface and provides an implementation for its `Move()` method.

Structure:

The structure of interfaces is quite simple yet powerful. They allow us to define contracts that must be fulfilled by any class implementing them .

Interfaces can contain methods, properties, indexers, and events, similar to classes, but without any implementation. They can also inherit from other interfaces, allowing us to build a hierarchy of interfaces.

One crucial aspect of interfaces is that they cannot be instantiated as they do not have any implementation. However, we can create references of an interface type and use them to store objects of classes that implement the interface.

Another crucial aspect is that a class can implement multiple interfaces. This allows for achieving multiple inheritance-like behavior without some of the downsides associated with traditional multiple inheritance.

public interface ICanine
{
  void Bark();
}

public class Dog : IAnimal, ICanine
{
  public void Move()
  {
    Console.WriteLine("Running on four legs");
  }

  public void Bark()
  {
    Console.WriteLine("Barking loudly");
  }
}

In the above example, the `Dog` class implements both `IAnimal` and `ICanine` interfaces.

  Hands-on Examples with Code Samples

In this section, we will provide you with hands-on examples on how to implement interfaces in C# using code samples. These examples will help you understand the concepts and syntax of interfaces better and give you a practical understanding of their usage.

Before we dive into the code samples, let’s quickly revisit what interfaces are and why they are useful in C#. As mentioned before, an interface is like a contract that guarantees certain functionality to be present in any class that implements it. This helps in achieving loose coupling between classes and enables flexibility in design. Now, let’s see some real-world scenarios where interfaces can come handy.

Example 1: Creating an Interface for a File Reader Class
In this example, we will create an interface called IFileReader which will require any class implementing it to have a ReadFile() method that takes in a file path as its parameter and returns the contents of the file. We will also create two classes that implement this interface – TextFileReader and ExcelFileReader.

public interface IFileReader
{
  string ReadFile(string filePath);
}

public class TextFileReader : IFileReader
{
  public string ReadFile(string filePath)
  {
    // code to read text file from given file path
    return text;
  }
}

public class ExcelFileReader : IFileReader
{
  public string Readile(string filePath)
  {
    // code to read excel file from given file path
    return excelData;
  }
}

  – Explanation of Multiple Inheritance using Interfaces

In object-oriented programming, inheritance is a mechanism that allows a class to inherit the properties and methods of another class. This allows for code reuse and structuring of classes in a hierarchical manner. In C#, it is also possible for a class to inherit from multiple classes, known as multiple inheritance.

However, C# does not support multiple inheritance through classes, but through interfaces. An interface can be seen as a contract that specifies what properties and methods a class must implement. Unlike classes, an interface cannot contain any implementation code and serves only as a blueprint for implementing specific behaviors.

Now let’s dive into the concept of multiple inheritance using interfaces in more detail.

To understand how multiple inheritance works with interfaces, let’s take an example scenario where we have two different interfaces – “IAnimal” and “IBird”, each with its own set of properties and methods. And we have two classes – “Dog” and “Sparrow” – which need to inherit from both these interfaces.

public interface IAnimal
{
  void Eat();
  void Sleep();
}

public interface IBird
{
  void Fly();
  bool HasFeathers { get; set; }
}

public class Dog : IAnimal
{
  public void Eat()
  {
    //Implementation code for eating behavior
  }

  public void Sleep()
  {
    //Implementation code for sleeping behavior
  }
}

public class Sparrow : IBird
{
  public bool HasFeathers { get; set ; }

  public void Fly()
  {
    //Implementation code for flying behavior
  }
}

In the above example, both classes – “Dog” and “Sparrow” – implement their respective interfaces. This means that they must provide an implementation for all the methods declared in the interfaces they are inheriting from.

Now if we want to have a class – “FlyingDog” – that exhibits both the behaviors of a dog and a bird, we can achieve this by inheriting from both “IAnimal” and “IBird”.

public class FlyingDog : IAnimal, IBird
{
  public bool HasFeathers { get ; set; }

  public void Eat()
  {
    //Implementation code for eating behavior
  }

  public void Sleep()
  {
    //Implementation code for sleeping behavior
  }

  public void Fly()
  {
    //Implementation code for flying behavior
  }
}

The class “FlyingDog” now has access to all the properties and methods defined in both interfaces. This allows us to define different behaviors for different types of animals without having to repeat code.

However, it is important to note that implementing multiple inheritance through interfaces also has its limitations. Unlike classes, interfaces cannot have fields or constructors. Also, if there are any conflicting members in the interfaces being inherited from (i.e. same method with different implementations), the implementing class must provide an explicit implementation for that member.

  – Step-by-step guide on Mastering C# Interface:

C# is an object-oriented programming language that offers a powerful and versatile way to organize code and create reusable components. One of the key features of C# is its interface, which serves as an essential tool for designing and implementing well-structured applications.

In this step-by-step guide, we will take you through the fundamental concepts of C# interfaces and how to master them in your coding journey. We have also included hands-on code samples that will help you understand the concepts better and apply them in practical scenarios.

Step 1: Understanding Interfaces
The first step towards mastering C# interfaces is to have a clear understanding of what they are and how they work. An interface acts as a contract between a class or struct and the outside world, providing a set of members that must be implemented by any class or struct that implements it.
An interface can contain properties, methods, events, or indexers without containing any implementation details. This means it only defines the structure that must be followed by implementing classes or structs.
To define an interface in C#, we use the “interface” keyword before its name. For example:

public interface IShape
{
  void Draw();
}

Step 2: Implementing Interfaces
Once we have defined our interface, we can implement it in our classes or structs using the “implements” keyword. By doing so, we are essentially agreeing to abide by the rules set by the contract defined in the interface.
Let’s take a look at an example of a class implementing our “IShape” interface:

public class Square : IShape
{
  public void Draw()
  {
    Console.WriteLine("Drawing a square.");
  }
}

As you can see, the “Square” class implements the “Draw()” method defined in the “IShape” interface.

Step 3: Implementing Multiple Interfaces
C# allows a single class or struct to implement multiple interfaces. This is useful when we want our class to inherit functionality from multiple sources. To do this, we simply separate each interface with a comma. Let’s use the previous example and add another interface called “IResizable”:

public interface IResizable
{
  void Resize();
}

public class Square : IShape, IResizable
{
  public void Draw()
  {
    Console.WriteLine("Drawing a square.");
  }

  public void Resize()
  {
    Console.WriteLine("Resizing the square.");
  }
}

Step 4: Interface Inheritance
Similar to classes, interfaces can also inherit from other interfaces. This means an interface can extend or refine another interface by adding new members or redefining existing ones.
Let’s take a look at an example of interface inheritance:

public interface IShape
{
  void Draw();
}

public interface ICircle : IShape
{
  void Fill();
}

As you can see, the “ICircle” interface is inheriting from the “IShape” interface. This means any class that implements the “ICircle” interface must also implement the “Draw()” method from the “IShape” interface.

Step 5: Default Interface Implementation (C# 8.0 and above)
Starting from C# 8.0, interfaces can also contain default implementations for their members. This feature is useful when we want to provide a default implementation for some methods in our interface, but still allow classes implementing it to override or modify those methods if needed.
To define a default implementation, we use the “default” keyword followed by the method body in our member declaration. Let’s take a look at an example:

public interface IResizable
{
  void Resize();

  // Note: The default implementation below is only available in C# 8.0 and above.
  // For older versions of C#, this will result in a compilation error.
  // To make your code backwards compatible, use explicit implementations .
  public void AutoResize()
  {
  Console.WriteLine("Automatically resizing the shape.");
  }
}

Step 6: Explicit Interface Implementation
Interfaces provide a way to implement multiple inheritance in C#. However, this can lead to naming conflicts when two interfaces contain members with the same name. In such cases, we have to use explicit interface implementation to differentiate between the two implementations.
To do this, we use the interface name followed by a dot (.) before the member name. Let’s take a look at an example:

public interface IResizable
{
  void Resize();
}

public interface IDeletable
{
  void Delete();
}

public class Shape : IResizable, IDeletable
{
  // Implementation of IResizable.Resize().
  public void Resize()
  {
    Console.WriteLine("Resizing the shape.");
  }

  // Implementation of IDeletable.Delete().
  public void Delete()
  {
    Console.WriteLine("Deleting the shape.");
  }

  // Explicit implementation of IResizable.Resize().
  void IResizable.Resize()
  {
    Console.WriteLine("Explicitly resizing the shape.");
  }
}

Note: When using explicit interface implementation, the method will only be accessible through an instance of the interface. This means we cannot access it using an instance of the class itself.

Step 7: Using Interfaces in a Practical Scenario
Now that we have covered the basics of C# interfaces, let’s look at how we can use them in a real-world scenario. Imagine you are building a drawing application, and you want to create different shapes like circles, squares, and rectangles. Each shape should be able to be resized and deleted. How can interfaces help us here?

First, we define our “IDrawable” interface that has the “Draw()” method:

public interface IDrawable
{
  void Draw();
}

Next, we define our “IShape” interface that inherits from the “IDrawable” interface and adds the “Resize()” and “Delete()” methods:

public interface IShape : IDrawable
{
  void Resize();
  void Delete();
}

Then, we can create separate classes for each shape type that implement the “IShape” interface:

public class Circle : IShape
{
  public void Draw()
  {
    Console.WriteLine("Drawing a circle.");
  }

  public void Resize()
  {
    Console.WriteLine("Resizing the circle.");
  }

  public void Delete()
  {
    Console.WriteLine("Deleting the circle.");
  }
}

// Similar classes for Square and Rectangle.

Finally, in our drawing application, we can use the interface as the type for our shape objects, allowing us to call any of the interface’s methods without knowing which specific shape we are dealing with:

IShape circle = new Circle();
circle.Draw(); // Outputs: "Drawing a circle."
circle.Resize(); // Outputs: "Resizing the circle."
circle.Delete(); // Outputs: "Deleting the circle."

Congratulations! You have now mastered C# interfaces. These powerful tools offer a flexible and organized way to structure your code and create reusable components. With this step-by-step guide, you should now have a clear understanding of how interfaces work and how to use them in your own coding projects. Keep practicing and exploring different scenarios to further enhance your skills with C# interfaces.