Do abstract class have Constructors in C#?

Yes, abstract classes can have constructors in C# just like any other class. Constructors are special methods used for initializing the state of an object when it is created.

The reason is, when the abstract class is inherited in the derived class, and whenever the object of the derived class is created then FIRST the constructor of the abstract/ base class will be called and then only the constructor of derived class will be called.

Here's an example of an abstract class with a constructor:

csharp
public abstract class MyBaseClass { protected MyBaseClass() { // Constructor logic } // Other members and methods }

In the above example, the MyBaseClass abstract class has a constructor defined with the protected access modifier. The protected keyword allows the constructor to be accessed by derived classes but not by instances of the abstract class directly.

Constructors in abstract classes are useful for initializing common fields or performing common initialization logic that is shared among derived classes. Derived classes can invoke the base class constructor using the base keyword in their own constructors to ensure proper initialization of the inherited members.

Note that since abstract classes cannot be directly instantiated, their constructors are typically called implicitly when creating instances of derived classes.

Here's an example of a derived class invoking the base class constructor:

csharp
public abstract class MyBaseClass { protected MyBaseClass(string message) { Console.WriteLine(message); } } public class MyDerivedClass : MyBaseClass { public MyDerivedClass() : base("Initializing MyDerivedClass") { // Derived class constructor logic } }

In this example, the derived class MyDerivedClass extends the abstract class MyBaseClass and invokes the base class constructor using the base keyword. The message "Initializing MyDerivedClass" will be printed when creating an instance of MyDerivedClass due to the invocation of the base class constructor.


 

Post a Comment

Previous Post Next Post