 |
Here's a simple OOP quiz for you...Assuming you have
the following class hierarchy courtesy of ASP.NET, if you have the following
code:
public
class Foo
{
public
static
void Bar(HtmlContainerControl
control) {
Console.WriteLine(control.GetType().Name);
}
}
Which of the following code snippets are valid and which are not? Why?
| A) |
|
| B) |
HtmlControl
c = null;
Foo.Bar(c);
|
| C) |
HtmlContainerControl
cc = null;
Foo.Bar(cc);
|
| D) |
Foo.Bar(new
HtmlImage());
|
| E) |
Foo.Bar(new HtmlTable());
|
|
To view the answers, highlight the next couple of lines...
Only C and E are valid. Let's start with why the other answers are not
correct? Simple enough: HtmlContainerControl is the type we need to match up
with in the function Foo.Bar(). Although HtmlContainerControl derives from
HtmlControl which in turn derives from Control, those classes higher up in the
hierarchy may not contain members defined in HtmlContainerControl. D is
incorrect because an HtmlImage is not guaranteed to contain the same structure
(class members) defined in HtmlContainerControl. However, it is quite obvious
why C is correct (if you missed that one, get another cup of coffee or
something). E is also correct because an HtmlTable derives from
HtmlContainerControl and therefore contains all of the members defined in
HtmlContainerControl. An easy rule to remember with inheritance is the "is a"
rule. An HtmlContainerControl is a HtmlContainerControl, and an HtmlTable
is a HtmlContainerControl.