What is the use of private constructor in abstract class in c#?

718 Views Asked by At

I face the below question in the interview.

Q1.Can we have a private constructor in the abstract class?

Answer- Yes, I gave an answer we can have then he again ask why and what is the use of the private constructor. I'm not able to answer to this cross-question. Can anybody explain this? with practically in c# will great help.

1

There are 1 best solutions below

0
Jon Skeet On BEST ANSWER

I can think of two uses:

Firstly, for chaining. You might have multiple protected constructors, but want to execute common code in all of them:

public abstract class Foo
{
    protected Foo(string name) : this(name, 0)
    {
    }

    protected Foo(int value) : this("", value)
    {
    }

    private Foo(string name, int value)
    {
        // Do common things with name and value, maybe format them, etc
    }
}

The second use would be to make it so that the only possible derived classes would be nested classes, which have access to private members. I've used this before when I want to enforce a limited number of derived classes, with instances usually exposed via the base class

public abstract class Operation
{
    public static readonly Operation Add { get; } = new AddOperation();
    public static readonly Operation Subtract { get; } = new SubtractOperation();

    // Only nested classes can use this...
    private Operation()
    {
    }

    private class AddOperation : Operation
    {
        ...
    }

    private class SubtractOperation : Operation
    {
        ...
    }
}