Saturday, July 07, 2007

base Keyword in .Net

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. SYNTAX.
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:

Most Recent Post

Subscribe Blog via Email

Enter your email address:



Disclaimers:We have tried hard to provide accurate information, as a user, you agree that you bear sole responsibility for your own decisions to use any programs, documents, source code, tips, articles or any other information provided on this Blog.
Page copy protected against web site content infringement by Copyscape