views:

128

answers:

4

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.

+2  A: 

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();

jasonh
Hmm actually this does work well, but I would have to change the calls. Using the event handler which should have been in my class to begin with.
Coding Monkey
Well, I'm slightly confused then. You're saying that you don't want to modify your app, class1 or logger? How do you get the event system in then?
jasonh
I was meaning that I didn't want to update the class if possible, but what I really meant to say was that I didn't want to make the classes relying on each other.
Coding Monkey
Gotcha. Thanks for the clarification!
jasonh
+5  A: 

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.

Jon Skeet
Isn't this what an extension method was designed for?
jasonh
That is perfect. Now I just have to understand how it works. I get the first part, but I presume that the part after the => is the part that replaces the delegate {} in the event handler in class1.
Coding Monkey
@Coding Monkey: => means lambda expression. In this case it's just an easy way of creating a delegate. It doesn't *replace* the original no-op handler; it adds a *new* handler. Will edit with a link to my events article when I'm on a PC again.
Jon Skeet
@jasonh: You could write an extension method so you could call class1.Execute(logger) each time, certainly - but I suspect that the normal desirable behaviour is for the logger to stay with class1 implicitly. Extension methods don't allow you to add new state.
Jon Skeet
@Jon Skeet: I see what you're saying. My method ties the two together explicitly, which I can see can be undesirable. I guess it all depends on the exact design of the program.
jasonh
A: 

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.

Jon Limjap
A: 

This is a small little tutorial on Event Handling. I hope this helps you.

Link

Aamir