Inheritance

Inherited Constructors

Much like methods and properties, constructors can also be implemented in base classes. This has effect of enforcing that your derived types also provide a strict set of constructor arguments to initialize the base type.

using System; public class Message { ...

 

In the example above, we've declared a type called Message which has a constructor. This constructor means that a derived class must provide arguments. This can be done using the base notation:

public Email() : base("Message")
{   
}

These arguments could be constant values, the results of expressions, or simply parameters provided by their own constructor:

public Email(string header) : base(header)
{
}

If you attempt to define a type that doesn't provide the right arguments, your code will not compile.

There is an exception to this rule, and that is, if a base class defines a public constructor with no arguments, then your derived class doesn't explicitly have to provide a constructor:

public class Message
{
    public Message()
    {
    }
}

public class Email : Message
{
    // No constructor is required.
}

 

Page 10 of 18