python ruby-programming-language Smalltalk Vue.js Knockoutjs TypeScript JavaScript, OOPs JavaScript Angular 8,7,6,5,4 and 2 Interview Questions and Answers Angular 8,7,6,5,4 and 2 Interview Questions and Answers Angular 4 Angular 2 AngularJs 1.x NodeJs Perl Programming R Programming RequireJs Rust Programming Backbonejs closure programming language go-programming-language kotlin-programming-language
constructor calling in inheritance

Best Use of C# Constructors In Inheritance [How To]


//We have two classes, one is ClassA and other is ClassB, the ClassB inherit base class ClassA.
//If we make the object of child class ClassB then which class constructor called first?
namespace ConsoleNamespace
{
    class ClassA
    {
        public ClassA()
        {
            Console.WriteLine("ClassA::Constructor()");
        }
    }
    class ClassB : ClassA
    {
        public ClassB()
        {
            Console.WriteLine("ClassB::Constructor()");
        }
    }
    class Test
    {
        static void Main(string[] args)
        {
            ClassB a = new ClassB();
            Console.ReadLine();
        }
    }
}

The output is base class "ClassA" constructor called first. i.e. (ClassA::Constructor())



Example 2
//If child constructor is missing the parent constructor is called.
namespace ConsoleNamespace
{
    class ClassA
    {
        public ClassA()
        {
            Console.WriteLine("ClassA::Constructor()");
        }
    }
    class ClassB : ClassA
    {

    }
    class Test
    {
        static void Main(string[] args)
        {
            ClassB a = new ClassB();
            Console.ReadLine();
        }
    }
}

OutPut: ClassA::Constructor()

Example 3
//If parent constructor is missing the child constructor is called.
namespace ConsoleNamespace
{
    class ClassA
    {

    }
    class ClassB : ClassA
    {
        public ClassB()
        {
            Console.WriteLine("ClassB::Constructor()");
        }
    }
    class Test
    {
        static void Main(string[] args)
        {
            ClassB a = new ClassB();
            Console.ReadLine();
        }
    }
}


Output : ClassB::Constructor()


ANIL SINGH

Hi there! Welcome to my blog. My name is Anil Singh. I'm a author of this blog. For more detail about me, kindly refer to this link..
My Blogs - http://code-sample.com and http://code-sample.xyz
My Books - Interview Questions and Answers Books- Get Your Book in 15+ Digital Stores Worldwide..

You Might Also Like
www.code-sample.com/. Powered by Blogger.
ASK Questions