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){}
}
Far as I know we can't instantiate an abstract class
There's your error right there. Of course you can instantiate an abstract class.
abstract class Animal {}
class Giraffe : Animal {}
...
Animal animal = new Giraffe();
There's an instance of Animal right there. You instantiate an abstract class by making a concrete class derived from it, and instantiating that. Remember, an instance of a derived concrete class is also an instance of its abstract base class. An instance of Giraffe is also an instance of Animal even if Animal is abstract.
Given that you can instantiate an abstract class, it needs to have a constructor like any other class, to ensure that its invariants are met.
Now, a static class is a class you actually cannot instantiate, and you'll notice that it is not legal to make an instance constructor in a static class.
It's a way to enforce a set of invariants of the abstract class. That is, no matter what the subclass does, you want to make sure some things are always true of the base class... example:
abstract class Foo
{
public DateTime TimeCreated {get; private set;}
protected Foo()
{
this.TimeCreated = DateTime.Now;
}
}
abstract class Bar : Foo
{
public Bar() : base() //Bar's constructor's must call Foo's parameterless constructor.
{ }
}
Don't think of a constructor as the dual of the new
operator. The constructor's only purpose is to ensure that you have an object in a valid state before you start using it. It just happens to be that we usually call it through a new
operator.