C# Constructors

The C# constructor syntax is odd.

MyClass : MyAncestor
{
    public MyClass(int Foo) : base(Foo + 1)
    {
       // implementation ommited
    }
}

You can’t directly call the ancestor.
However you are allowed to make manipulations on the data.
You can even invoke static methods on the class that you are creating:

MyClass : MyAncestor
{
    public MyClass(int Foo) : base(Bar(Foo))
    {
       // implementation ommited
    }

    static int Bar(int Foo)
    {
       return Foo + 1
    }
}

This does allow a certain amount of flexibility.
However since static methods cannot be virtual you can’t quite reach the flexibility of Delphi.
Delphi would allow a virtual method to be called that can set values before the inherited constructor is called. This can be very useful in some situations.For example if the ancestor is creating a font you could have a descendant choose whether the font is bold.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s