Coding Monkey
Coding Monkey

Reputation: 1000

Add an event to a class method?

OK, I've tried but I just don't get it.

I have two classes logger and class1.

I have a method called logger.Write(string) and method called class1.Execute().

Now in my application I want to have logger.Write(class1.ToString()) run when class1.Execute() is called.

I presume you need to add delegates and events, but I just can't get my head around this, been scratching it for a couple hours.

One thing, is that the logger and the class are in different namespaces and I don't want to update the class code for either of them if possible.

Upvotes: 0

Views: 510

Answers (3)

Jon Limjap
Jon Limjap

Reputation: 95432

You'll need to declare an EventHandler for Class1

public event EventHandler OnExecute;

and in your execute method:

public void Execute()
{
   //...
   if (OnExecute != null)
       OnExecute(this, null);
}

And then when you use class1 elsewhere, that's where you put your event;

private Class1 class1 = new Class1();
class1.OnExecute += SomeMethodName;

public void SomeMethodName(sender obj, EventArgs e)
{
    logger.Write(class1.ToString());
}

We can make custom EventHandlers for if you want more information there, but for barebones parameterless events this should work.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1499860

Well you certainly can't do it without changing code in either class (assuming you also don't want to change everywhere that calls class1.Execute) - at least not without some deep code-weaving/instrumentation magic. However, you can fairly easily add an event in Class1:

public class Class1
{
    // TODO: Think of a better name :)
    public event EventHandler ExecuteCalled = delegate {};

    public void Execute()
    {
        ExecuteCalled(this, EventArgs.Empty);
        // Do your normal stuff
    }
}

The delegate{} bit is just to make sure that there's always at least a no-op event handler registered - it means you don't need to check for nullity.

You'd then hook it up by writing:

Class1 class1 = new Class1();
Logger logger = new Logger();
class1.ExecuteCalled += (sender, args) => logger.Write(sender.ToString());

(This is assuming you're using C# 3 so you have lambda expressions available to you - let me know if that's not the case.)

If Class1 implements an interface (say IFoo), you might want to write an implementation of the interface which wraps another implementation, and just logs before each call:

public sealed class LoggingFoo : IFoo
{
    private readonly IFoo original;
    private readonly IFoo logger;

    public LoggingFoo(IFoo original, Logger logger)
    {
        // TODO: Check arguments for nullity
        this.original = original;
        this.logger = logger;
    }

    // Implement IFoo
    public void Execute()
    {
        logger.Write("Calling Execute on {0}", original);
        original.Execute();
    }
}

Then just use that wrapper around a "real" implementation wherever you currently just use the implementation.

Upvotes: 6

jasonh
jasonh

Reputation: 30293

Can you pass an object parameter for logger and then just call the ToString on that? The proper ToString method will be called. If you don't want to change anything in logger or class1, then you could write an extension method and call that instead of calling class1.Execute. This method would make the call to logger and then the call to class1.Execute.

public static ExecuteAndLog(this class1 obj)
{
    logger.Write(obj.ToString());
    obj.Execute();
}

And then you'd simply call obj.ExecuteAndLog();

Upvotes: 2

Related Questions