C#: The base keyword in constructor

This entry is part 54 of 71 in the series C#

To invoke a non-default constructor in the base class when creating an instance of a subclass, you can use the base keyword.

For example, change the constructor in Actress to the following to invoke the second constructor in Star.

using System;

namespace DefConstruct
{
    class Program
    {
        class Star
        {
            public Star()
            {
                Console.WriteLine("Star()");
            }
            public Star(string name)
            {
                Console.WriteLine("Star() " + name);
            }
        }

        class Actress : Star
        {
            public Actress(string name) : base (name)
            {
                Console.WriteLine("Actress() " + name);
            }
        }

        static void Main()
        {
            Actress actress = new Actress("Susan Sarandon");
            Console.ReadKey();
        }
    }
}

The output from running the above code will be:

Star() Susan Sarandon
Actress() Susan Sarandon

Series Navigation<< C#: Base Class’ Constructors
C#: Accessing base class’ hidden members >>