Sunday, July 25, 2010

C# tip 7/25/2010

Implement interfaces versus overriding functions:

 
interface IBase
{
  void method();
}

 
class Base : IBase
{
  public void method()
  {
    Console.WriteLine("base implementation of method()");
  }
}

 
Console.WriteLine("first implementation:");
Console.WriteLine("call base");
Base b = new Base();
b.method();
Console.WriteLine("call ibase");
IBase i = b;
i.method();

 
This yields:
 
So far so good.  But what if you wanted to override the base method?

adding a new class throws a compiler error(class is below):

class Derived : Base
{
  public void method()
  {
    Console.WriteLine("derived implementation of method()");
  }
}

 
The error (actually a warning but you should treat all warnings as errors), is the following:

Error 1 Warning as Error: 'TipTester.Derived.method()' hides inherited member 'TipTester.Base.method()'. Use the new keyword if hiding was intended.


Solution is to add the new keyword to the derived method.
public new void method()

{
  Console.WriteLine("derived implementation of method()");
}

 
Modifying the main method to read the following:
Console.WriteLine("first implementation:");

Console.WriteLine("call derived");
Derived d = new Derived();
d.method();
Console.WriteLine("call base");
Base b = d;
b.method();
Console.WriteLine("call ibase");
IBase i = d;
i.method();
 

Yields the following:

Problem:  when calling the derived method directly, the right method is called; however, when casting the derived class to the base class or to the interface, the base class implementation is called.  This is because the class is not really inherited.

Solution:

1. For the interface: make the derived class implement the interface directly (this is going to get clumsy fast).  This solution also does not fix the base class problem.

2, Make the base class method virtual and the derived method override the base method.  This implementation fixes all the inheritance issues.  The new implementation of base and derived methods are the following:

                   public virtual void method()

                   {
                     Console.WriteLine("base implementation of method()");
                   }

 

                   public override void method()
                   {
                     Console.WriteLine("derivedbase implementation of method()");
                   } 

3. Best implementation, however, would be to make the base method abstract and force the derived methods to implement it. This might not be optimal for those situations where you might not want to implement the abstract method every time.

No comments:

Labels