Is it possible to add a custom property to an object that is part of the .NET framework?
I know how I would do this if I was just giving a class i’d wrote a property, but what about adding a custom property to the FileSystemWatcher class?
I’m loading in the Path I want to watch from an XML file, but also want to add a property to store more information, in this case the location of a config file. Can I add this property to the FileSystemWatcher class itself?
So you want to inherit all the functionalities of the
FileSystemWatcher, while adding your properties?Try inheriting the class:
and after that you can use your new class on every place where you would use the
System.IO.FileSystemWatcher, like this:Another approach would be to make a class that will both have the config file location , and the FileSystemWatcher object as a property, along these lines:
and with usage like this:
Composition is possible even when the base class cannot be inherited, and it’s generally preferred from an OO perspective, since most of the code that uses your class will rely only on your class, and not on the base class. However, when you do want to inherit all of the base behaviours and just add some (well-defined) extras, inheritance is the simpler and more tightly-coupled solution.