views:

784

answers:

5

Hi, I have a problem. I have a base class vehicle and some children classes like car, motorbike etc.. inheriting from vehicle. In each children class there is a function Go(); now I want to log information on every vehicle when the function go fires, and on that log I want to know witch kind of vehicle did it. example:

public class vehicle 
{
      public void Go()
      {
           Log("vehicle X fired");
      }
}
public class car : vehicle
{
       public void Go() : base()
       {
           // do something
       }
}


How can I know in the function Log that car called me during the base()? Thanks,

Omri

+14  A: 

Calling GetType() from Vehicle.Go() would work - but only if Go() was actually called.

One way of enforcing this is to use the template method pattern:

public abstract class Vehicle 
{
    public void Go()
    {
        Log("vehicle {0} fired", GetType().Name);
        GoImpl();
    }

    protected abstract void GoImpl();
}

public class Car : Vehicle
{
    protected override void GoImpl()
    {
        // do something
    }
}
Jon Skeet
+2  A: 

this.GetType() will give you the type of the current instance

Joe
+2  A: 

How about this:

GetType().Name
Brian Genisio
A: 

Thanks,

Omri.

Omri
+2  A: 

Jon Skeet's reply certainly gets the job done, but I for one do not really like the implementation. I prefer the following which keeps it - in my opinion - simple.

Anyway, .NET provides support for this functionality already by way of virtual methods.

public class Vehicle {
    public virtual void Go() {
          Log(this.GetType().Name);
    }
}

public class Car : Vehicle {
    public override void Go() {
         base.Go();
         // Do car specific stuff
    }
}

public class Bus : Vehicle {
}

This will work wether you are refering to an instance by it's base class or its actual class. It does not force you to change the implementation in base clases and well... all the other object orientated niceness of .NET.

If you have full control over the implementation of the base and derived classes, then this implementation should serve you nicely.

Barry Jones
The point is that skeets pattern forces people to use Log, while yours calling base.Go() is entirely optional.
FlySwat