Search code examples
c#eventsc#-4.0filesystemwatcher

Can you add an object to a c# watcher?


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


Solution

  • 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.