Friday, May 12, 2023

Abstract class in C#

What is an abstract class in C#?


 In C#, an abstract class is a class that cannot be instantiated directly, but can be used as a base class for other classes. An abstract class is designed to be inherited by other classes, and it provides a base implementation for its derived classes.


An abstract class can contain both abstract and non-abstract members. An abstract member is a member that is declared without implementation, meaning that it has no method body. Derived classes must provide an implementation for all abstract members of the abstract class.


Here's an example of an abstract class:



abstract class clsShape

{

    public abstract double GetArea();

}



In this example, the "clsShape" class is declared as abstract, which means that it cannot be instantiated directly. The class has an abstract method called "GetArea", which is declared without implementation. This means that any class that derives from the "clsShape" class must provide an implementation for the "GetArea" method.


Here's an example of a class that derives from the "clsShape" class:


class clsRectangle : clsShape

{

    public double Width { get; set; }

    public double Height { get; set; }


    public override double GetArea()

    {

        return Width * Height;

    }

}


In this example, the "clsRectangle" class derives from the "clsShape" class 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.


Abstract classes are useful for creating a hierarchy of related classes that share common functionality. They provide a way to define a set of methods and properties that derived classes must implement, while also providing a default implementation for those members that can be reused by the derived classes. Abstract classes cannot be instantiated directly, but they can be used as a type for variables, parameters, and return values.

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...