Sobes.tech
Junior — Middle

Is it possible to extend a class by adding a constructor with arguments?

sobes.tech AI

Answer from AI

Yes, in C# you can extend a class by adding a constructor with arguments, but with some limitations.

If you create a subclass (derived class), it can have its own constructors with arguments. However, if the base class does not have a default constructor (without parameters), then the derived class constructor must explicitly call the base class constructor with the required parameters using base(...).

Example:

class BaseClass
{
    public BaseClass(int x) { /* ... */ }
}

class DerivedClass : BaseClass
{
    public DerivedClass(int x, string y) : base(x)
    {
        // additional initialization with y
    }
}

If you are talking about extending the class itself (for example, through partial class or extension methods), then adding a constructor via extension methods is not possible — constructors cannot be defined in extensions. In this case, you need to modify the original class code or create a subclass with the desired constructors.