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)
Comments
Post a Comment