Constructor of an Abstract Class in C#

Constructor of an abstract class in C#

Because there might be a standard way you want to instantiate data in the abstract class. That way you can have classes that inherit from that class call the base constructor.

public abstract class A{

private string data;

protected A(string myString){
data = myString;
}

}

public class B : A {

B(string myString) : base(myString){}

}

Abstract class with constructor, force inherited class to call it

A class without an explicit constructor has a parameterless constructor. In the other hand, if you implement a constructor with parameters and no paramterless constructor, your class won't be instantiable without arguments.

In other words:

public abstract class A 
{
public A(string x)
{
}
}

public class B : A
{
// If you don't add ": base(x)"
// your code won't compile, because A has a
// constructor with parameters!
public B(string x) : base(x)
{
}
}

That is, if A has a parameterless constructor (or no explicit constructor), B will automatically call the base constructor. You don't need to code any further stuff here.

Otherwise, if your base class has a parameterless constructor and a constructor with parameters, you can't force a derived class to automatically call a constructor excepting the default one (i.e. the so-called parameterless constructor).

Workaround

Well, there's no special workaround here, but be aware C# supports optional parameters in both constructors and methods.

If you want to be 100% sure derived classes will call a concrete base constructor, you can implement your base class using a single parameterless constructor with optional parameters and use this instead of constructor overloading:

public class A
{
public A(string x = "hello world") // or just string x = null
{

}
}

Now if a B class derived A, B will always call A's base constructor, since x is optional and it has a default value.

Abstract class constructor in C#

Good question. Here's why Abstract classes need constructors even though they cannot be instantited.

In any Object oriented language like C#, object construction is an hierarchical process. Look at the code below. When you instantiate any object of type DerivedClass, it must construct the base object first before creating the object of typeof DerivedClass. Here the base class may or may not be an Abstract class. But even when you instantiate an object of a concrete type derived from an abstract class it will still need to call the constructor of the Base class before the object of DerivedClass type is created, hence you always need a constructor for Abstract class. If you have not added any constructor, C# compiler will automatically add a public parameterless constructor to the class in the generated MSIL.

public class BaseClass
{
public BaseClass()
{
Console.WriteLine("BaseClass constructor called..");
}
}

public class DerivedClass : BaseClass
{
public DerivedClass()
{
Console.WriteLine("DerivedClass constructor called..");
}
}

DerivedClass obj = new DerivedClass();

//Output
//BaseClass constructor called..
//DerivedClass constructor called..

PS: Assuming, If Abstract base classes
are not allowed to have constructors
because they need not be instantiated,
the whole fundamentals of the object
oriented programming will go on toss.
The idea behind Abstract types are to
represent objects that have some
features and behaviours but not
complete as whole to allow independant
existence.

Is it good to have a constructor in abstract class?

Yes, it's absolutely fine. Just because the constructor can only be called by derived classes doesn't mean it won't be useful. For example, you might have an abstract class which represents a named entity of some kind - it would make sense to take the name as a constructor parameter.

It would probably be worth making the constructor protected, to make it even more obvious that you can't just call it from elsewhere.

Note that there being a constructor (or multiple constructors) in an abstract class does force derived class constructors to go through it, but it doesn't force the derived classes to have the same constructor signatures. For example:

public abstract class NamedFoo
{
private readonly string name;
public string Name { get { return name; } }

protected NamedFoo(string name)
{
this.name = name;
}
}

public class DerivedFooWithConstantName
{
public DerivedFooWithConstantName() : base("constant name")
{
}
}

In this case the derived class constructor is "removing" a parameter (by providing a constant value as the argument to the abstract class constructor) but in other cases it could "add" parameters that it required, or have a mixture.

Why can an abstract class have constructor?

One important reason is due to the fact there's an implicit call to the base constructor prior to the derived constructor execution. Keep in mind that unlike interfaces, abstract classes do contain implementation. That implementation may require field initialization or other instance members. Note the following example and the output:

   abstract class Animal
{
public string DefaultMessage { get; set; }

public Animal()
{
Console.WriteLine("Animal constructor called");
DefaultMessage = "Default Speak";
}
public virtual void Speak()
{
Console.WriteLine(DefaultMessage);
}
}

class Dog : Animal
{
public Dog(): base()//base() redundant. There's an implicit call to base here.
{
Console.WriteLine("Dog constructor called");
}
public override void Speak()
{
Console.WriteLine("Custom Speak");//append new behavior
base.Speak();//Re-use base behavior too
}
}

Although we cannot directly construct an Animal with new, the constructor is implicitly called when we construct a Dog.

OUTPUT:

Animal constructor called

Dog constructor called

Custom Speak

Default Speak

C# constructor for type parameterized abstract class

Remove <T> from the constructor declaration and then everything will work. For example, this compiles just fine:

public abstract class Cell<T>
{
int address;
T value;

protected Cell(int address, T value)
{

}
}

public class CellInt : Cell<int>
{
public CellInt(int address, int value): base(address, value) { }
}

Abstract constructor in C#

Constructors are only applicable to the class in which they are defined, that is, they are not inherited. Base class constructors are used (you have to call one of them, even if only calling the default one automatically) but not overridden by deriving classes. You can define a constructor on an abstract base class -- it can't be used directly, but can be invoked by deriving classes. What you can't do is force a derived class to implement a specific constructor signature.

It is perfectly reasonable to have a constructor defined, typically as protected, in order to define some common set up code for all derived classes. This is especially true, perhaps, when the abstract class provides some other default behavior which relies on this set up. For example:

public abstract class Foo
{
public string Name { get; private set; }

protected Foo( string name )
{
this.Name = name;
}
}

public class Bar : Foo
{
public Bar() : base("bar")
{
...
}
}

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

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

Why can't I create an abstract constructor on an abstract C# class?

You cannot have an abstract constructor because abstract means you must override it in any non-abstract child class and you cannot override a constructor.

If you think about it, this makes sense, since you always call the constructor of the child class (with the new operator) and never the base class.

Generally speaking, the only way in C# to enforce a specific constructor signature is by using the new() generic constraint, which enforces the existence of a parameterless constructor for the type parameter.



Related Topics



Leave a reply



Submit