C# Interface

In C#, an interface is a language construct that defines a contract or a set of methods and properties that a class must implement. It provides a way to define a common behavior that can be shared among multiple classes without specifying how that behavior is implemented.

To declare an interface in C#, you use the interface keyword followed by the name of the interface. Here’s an example:

public interface IExampleInterface
{
    void SomeMethod();
    int SomeProperty { get; set; }
}

In this example, we define an interface called IExampleInterface. It declares two members: a method called SomeMethod() and a property called SomeProperty. Interfaces can include methods, properties, events, and indexers.

To implement an interface in a class, you use the : symbol followed by the interface name. Here’s an example:

public class ExampleClass : IExampleInterface
{
    public void SomeMethod()
    {
        // Implementation of the SomeMethod() defined in the interface
    }

    public int SomeProperty { get; set; }
}

In this example, the ExampleClass implements the IExampleInterface interface by providing the necessary implementation for the SomeMethod() method and the SomeProperty property.

A class can implement multiple interfaces by separating them with commas. For example:

public class ExampleClass : IExampleInterface, IOtherInterface
{
    // Implementation of the interface members
}

By implementing an interface, a class commits to providing the defined behavior and adhering to the contract specified by the interface. This allows for a more flexible and modular code structure and enables polymorphism and abstraction.