Wednesday, December 05, 2012

‘Base’ in C#

Posted by Rahul Kharde at 11:16 PM

The base keyword is used to access members of the base class from within a derived class
Base is used in constructors. A derived class constructor is required to call the constructor from its base class. When the default constructor isn't present, the custom base constructor can, with base, be referenced. Base class has been overridden by another method.

Example  1

    public class ClassA
    {
        public virtual void Method1()
        {
            Console.WriteLine("ClassA");
        }
    }
    class ClassB : ClassA
    {
        public override void Method1()
        {
            base.Method1();
            Console.WriteLine("ClassB");
        }
    }
    class ClassC : ClassB
    {
        public override void Method1()
        {
            base.Method1();
            Console.WriteLine("ClassC");
        }
    }
   class Program
    {
        static void Main()
        {
            ClassC obj = new ClassC();
            obj.Method1();
        }
    }
Output
ClassA
ClassB
ClassC
Here, ClassA is base Class and ClassB and ClassC Are Drived classes and have a Method named Method1


Example 2

  public class ClassA
    {
        public ClassA()
        {
            Console.WriteLine ("In Base ClassA()");
        }

        public ClassA(int i)
        {
            Console.WriteLine ("In Base ClassA(i)");
        }
    }

    public class ClassB : ClassA
    {
        public ClassB() : base()
        {

        }
        public ClassB(int i) : base(i)
        {
        }
    }

    class Program
    {
        static void Main()
        {
            ClassB objB = new ClassB();
            ClassB ObjB1 = new ClassB(1);
        }
    }
Output

In Base ClassA()
In Base ClassA(i)


If you enjoyed this post and wish to be informed whenever a new post is published, then make sure you subscribe to my regular Email Updates. Subscribe Now!


Kindly Bookmark and Share it:

YOUR ADSENSE CODE GOES HERE

0 comments:

Have any question? Feel Free To Post Below:

 

Popular Posts

Recent Comments

© 2011. All Rights Reserved | Help to understand .Net | Template by Blogger Widgets

Home | About | Top