base keyword and calling base class constructor in .Net
Using the base keyword, you can access any of a base class public or protected class members.
Another way to access base class members is through an explicit cast.
The colon, ":", and keyword base call the base class constructor with the matching parameter list.
In below example, Inside the Child print() method, we explicitly call the Parent print() method. This is done by prefixing the method name with "base.".
using System;
public class Parent
{
string parentString;
public Parent()
{
Console.WriteLine("Parent Constructor.");
}
public Parent(string myString)
{
parentString = myString;
Console.WriteLine(parentString);
}
public void print()
{
Console.WriteLine("I'm a Parent Class.");
}
}
public class Child : Parent
{
public Child() : base("From Derived")
{
Console.WriteLine("Child Constructor.");
}
public new void print()
{
base.print(); //CALLING BASE CLASS METHOD, USING BASE.
Console.WriteLine("I'm a Child Class.");
}
public static void Main()
{
Child child = new Child();
child.print();
((Parent)child).print();
}
}
Output:From DerivedChild Constructor.
I'm a Parent Class.
I'm a Child Class.
I'm a Parent Class.
No comments:
Post a Comment