Friday, May 12, 2023

Interface in C#

 What is an interface in C#?


In C#, an interface is a contract that specifies a set of methods, properties, and events that a class must implement. An interface defines a set of rules for how classes can interact with each other, and provides a way to achieve polymorphism in object-oriented programming.


Here's an example of an interface:



public interface IShape

{

    double GetArea();

}



In this example, the "IShape" interface defines a method called "GetArea", which is used to calculate the area of a shape. Any class that implements the "IShape" interface must provide an implementation for the "GetArea" method.


Here's an example of a class that implements the "IShape" interface:



public class Rectangle : IShape

{

    public double Width { get; set; }

    public double Height { get; set; }


    public double GetArea()

    {

        return Width * Height;

    }

}



In this example, the "Rectangle" class implements the "IShape" interface and provides an implementation for the "GetArea" method. The class has properties for the width and height of the rectangle, and the "GetArea" method calculates the area of the rectangle by multiplying the width and height.


Interfaces are useful for creating a set of rules for how classes can interact with each other. They provide a way to define a common set of methods, properties, and events that classes must implement, while also allowing for different implementations of those members. Interfaces also provide a way to achieve polymorphism, allowing objects to be treated as different types at runtime based on their implementation of a shared interface.

No comments:

Post a Comment

If you have any query kindly let me know.

Blazor drawback| drawback of blazor| Disadvantage of blazor in c#

  Blazor drawback| drawback of blazor| Disadvantage of blazor in c# While Blazor offers many advantages, it also has a few drawbacks to cons...