Information Technology Reference
In-Depth Information
come up with a different name for a method, especially if the alternative
is confusion for everyone using your types.
The guidance here is straightforward, and yet people always question if it
really should be so strict. Maybe that's because overloading sounds very
much like overriding. Overriding virtual methods is such a core principle
of object-oriented languages; that's obviously not what I mean. Over-
loading means creating multiple methods with the same name and differ-
ent parameter lists. Does overloading base class methods really have that
much of an effect on overload resolution? Let's look at the different ways
where overloading methods in the base class can cause issues.
There are a lot of permutations to this problem. Let's start simple. The
interplay between overloads in base classes has a lot to do with base and
derived classes used for parameters. For all the following examples, any
class that begins with “B” is the base class, and any class that begins with
“D” is the derived class. The samples use this class hierarchy for parameters:
public class B2 { }
public class D2 : B2 {}
Here's a class with one method, using the derived parameter (D2):
public class B
{
public void Foo( D2 parm)
{
Console .WriteLine( "In B.Foo" );
}
}
Obviously, this snippet of code writes “In B.Foo”:
var obj1 = new D ();
obj1.Bar( new D2 ());
Now, let's add a new derived class with an overloaded method:
public class D : B
{
public void Foo( B2 parm)
{
Console .WriteLine( "In D.Foo" );
}
}
 
Search WWH ::




Custom Search