Implement method decorators in C#

c#, decorator, design-patterns, python

Solution

You can achieve something similar using Aspect Oriented Programming. I've only used PostSharp in the past but it's not free for commercial use though.

There are other AOP solutions out there and you can certainly achieve something similar using Mono.Cecil, but it would require more work.

Reza Ahmadi wrote a nice little introduction article called Aspect Oriented Programming Using C# and PostSharp. It can give you a clear enough idea of what to expect and how it works.

Problem

In `python` is possible to implement `function decorators` to extend the behavior of functions and methods. In particular I'm migrating a device lib from `python` to `C#`. The communication with device can generate errors which should reraised with custom exception. In `python` I would write like this: ``` @device_error_wrapper("Device A", "Error while setting output voltage.") def set_voltage(self, voltage): """ Safely set the output voltage of device. """ self.__handle.write(":source:voltage:level {0}".format(voltage)) ``` This method call would expand to ``` try: self.__handle.write(":source:voltage:level {0}".format(voltage)) except Error: raise DeviceError("Error while setting output voltage.", "DeviceA") ``` With this pattern you can easily wrap and extend methods without having to write every `try-except` clause in every method. Is it to possible to implement a similar pattern using `C#`? If the implementation of the decorator (`device_error_wrapper`) is needed, please tell.

Original source

Related problems