This is a mirror of official site: http://jasper-net.blogspot.com/

The Inheritance Problem

| Monday, January 10, 2011
Inheritance and function overloading don't play well together in C#. See if you can figure out the reasons that this puzzle doesn't work as you might expect.

Background

Object Oriented programming is wonderful and one of its most wonderful attributes is the ability to create new classes that inherit all of the methods and properties of existing classes.
Today there may be some worries about using inheritance and even a move towards claiming that it isn't a particularly safe construct but many programmers do make use of it within their projects because it is better than Copy and Paste inheritance that you often see in use when the Interface approach is used.
So leaving asside questions of the advisability of using inheritance let's see how this particular puzzle came about.
C# takes a very standard approach to objects. You can create a base class:

class Base
{
public void MyMethod(int i)
{
 MessageBox.Show("Base method Int");
}
}

create a derived class:

Class Derived : Base
{    
}

and even if the Derived class is empty it still has all of the properties and methods of the base class. So you can call MyMethod using an object of the Derived class:

Derived MyObject = new Derived();
MyObject.MyMethod(1);

Another useful feature of C#, although it isn't an object oriented one is function overloading - which always sounds as if it is a sort of cruely to functions. It isn't because it is incredibly useful.
Functions are not simply defined by their name i.e. MyMethod but the types of their parameters or signature. That is MyMethod is MyMethod(int). What this means is that you can define lots of methods with same name as long as their parameter lists i.e. signatures are different. Notice that the return type plays no role in the signature.
If you make a call to an overloaded function then the function definition with the most specific match to the call signature is the one that is actually used. For example, if we change the defintion of the Base class to:

class Base
{
public void MyMethod(int i)
{
 MessageBox.Show("Base method Int");
}
public void MyMethod(object i)
{
 MessageBox.Show("Base Method Object");
}
}

And make a the call

Derived MyObject = new Derived();
MyObject.MyMethod(1);

Read more: I Programmer

Posted via email from .NET Info

0 comments: