An Inheritance Question.

Q

Quentin Huo

Hi:

I have a parent class "classA", which is like:

public abstract class classA
{
.....

public string ReturnAString()
{
return "Hello, World";
}

......
}

And I have another class "classB" inheriting from "classA", like:

public class classB
{
......

public string AMethod()
{
return ReturnAString();
}

......
}

My question is: what is the difference if I change the statement
"ReturnAString();" in the method "AMethod" of the "classB" to:

return base.RetuenAString();

They both works well, but I want to know if there is any difference between
the two statements. The "base" here means an instance of its parent class
has been created? Or maybe they are totally same?

Thanks

Q.
 
B

Bruce Wood

There is only one subtle difference.

If, two years from now, you were to write another method in classB:

public new string ReturnAString()
{
return "Been around the world!";
}

then simply calling "ReturnAString();" in classB would result in "Been
around the world", while calling "base.ReturnAString()" would result in
"Hello, world".

In other words, unless there is also a method in classB called
ReturnAString, there is no difference at all. Most people don't worry
about the above scenario, and simply code "ReturnAString()",
understanding that it will invoke the base class method. Besides, if
you were to add a new ReturnAString() to classB, who's to say that you
don't want it called in that situation, and want the base method
instead?

I use "base." only when the derived class already has a method by that
name and I don't want to call it. The classic example is an override
that wants to make use of its base class functionality:

protected override void OnClick(object sender, System.EventArgs args)
{
// Do some special stuff here...

base.OnClick(sender, args);
}

I have to say "base." here because I don't want to invoke the same
method recursively... I want to add some of my own code and then
continue with the original implementation of OnClick.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top