When you create a class object
C#
Book3 book = new Book3();
Constructors will be called:
1st constructor will be invoked from the base class itself . In our example, it will be invoked Book1()
2nd constructor will be called at a class that inherits from the base . In our example, it will be invoked Book2()
...
constructors will be called up the inheritance . In our example, it will be invoked Book3()
C#
class Book1
{
// constructor
public Book1()
{
Console.WriteLine("Book1()");
}
}
class Book2 : Book1
{
public Book2()
{
Console.WriteLine("Book2()");
}
public Book2(string str)
{
Console.WriteLine("Book2({0})", str);
}
}
class Book3 : Book2
{
public Book3()
{
Console.WriteLine("Book3()");
}
}
class Program
{
static void Main(string[] args)
{
Book3 book = new Book3();
// on the screen we will see
// Book1()
// Book2()
// Book3()
}
}
To call the constructor from the base class you need to write:
C#
base(base constructor arguments);
C#
class Book1
{
// constructor
public Book1()
{
Console.WriteLine("Book1()");
}
}
class Book2 : Book1
{
public Book2()
{
Console.WriteLine("Book2()");
}
public Book2(string str)
{
Console.WriteLine("Book2({0})", str);
}
}
class Book3 : Book2
{
public Book3() : base("aaa")
{
Console.WriteLine("Book3()");
}
}
class Program
{
static void Main(string[] args)
{
Book3 book = new Book3();
// on the screen we will see
// Book1()
// Book2(aaa)
// Book3() }
}
1) 'base' can be used to call a method from a base class
2) 'base' can be used when a class variable matches a variable from the base class
More about base in the C# ...