Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order of calling constructors case of inheritance in c# [duplicate]

Tags:

c#

.net

c#-4.0

I was just reading Inheritance in C# in which i came across the Constructors and was written that constructors are executed in order of derivation. What does it mean?That base class constructor will be called first or Derived class.

like image 768
Eljay Avatar asked Feb 07 '12 05:02

Eljay


2 Answers

The base class constructor will be called first. You can test this pretty easily yourself:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DerivationTest
{
    class Program
    {
        public class Thing
        {
            public Thing()
            {
                Console.WriteLine("Thing");
            }
        }

        public class ThingChild : Thing
        {
            public ThingChild()
            {
                Console.WriteLine("ThingChild");
            }
        }

        static void Main(string[] args)
        {
            var tc = new ThingChild();
            Console.ReadLine();
        }
    }
}
like image 39
LiquidPony Avatar answered Oct 12 '22 23:10

LiquidPony


A base class Constructor is called first.Refer to the following example

// Demonstrate when constructors are called.
using System;

// Create a base class.
class A {
    public A() {
        Console.WriteLine("Constructing A.");
    }
}

// Create a class derived from A.
class B : A {
    public B() {
        Console.WriteLine("Constructing B.");
    }
}

// Create a class derived from B.
class C : B {
    public C() {
        Console.WriteLine("Constructing C.");
    }
}

class OrderOfConstruction {
    static void Main() {
        C c = new C();
    }
}

The output from this program is shown here:

Constructing A.
Constructing B.
Constructing C.
like image 178
Junior Bill gates Avatar answered Oct 12 '22 23:10

Junior Bill gates