0

When i create a watcher i want to add an object to it that i can read during the watchers watcher_Created event?

Andy
  • 2,248
  • 7
  • 34
  • 57

1 Answers1

4

You can just capture it in an anonymous delegate:

object o;
var watcher = new FileSystemWatcher();
watcher.Created += (sender, e) => { 
    Console.WriteLine(o);
    // handle created event
};

Here, o represents the object that you want to capture (it doesn't have to be typed as object).

Note that this is effectively the same as

class Foo {
    private readonly object o;
    public Foo(object o) {
        this.o = o;
    }

    public void OnCreated(object sender, FileSystemEventArgs e) {
        Console.WriteLine(this.o);
        // handle event
    }
}

object o = null;
Foo foo = new Foo(o);
var watcher = new FileSystemWatcher();
watcher.Created += foo.OnCreated;

but we have let the compiler do the work for us. There are subtle differences.

jason
  • 236,483
  • 35
  • 423
  • 525