In C#, can I know in the base class what children inherited from me?

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 which 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

Answers


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
    }
}

Need Your Help

Android: Sort JSONArray by object attribute

android json parsing arrays

I'm trying to create a list of "events" for an agenda.

Error adding value names to devise

ruby-on-rails ruby ruby-on-rails-3 devise

Im getting an error trying to add the value name to devise, I think all did all things to make it work, but it doesnt work.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.