Action on each method's return value
        Posted  
        
            by RobGlynn
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by RobGlynn
        
        
        
        Published on 2010-05-21T16:47:33Z
        Indexed on 
            2010/05/21
            16:50 UTC
        
        
        Read the original article
        Hit count: 192
        
c#
What I'd like to do is take some action using the value returned by every method in a class.
So for instance, if I have a class Order which has a method
public Customer GetCustomer()
{
 Customer CustomerInstance = // get customer
 return CustomerInstance;
}
Let's say I want to log the creation of these - Log(CustomerInstance);
My options (AFAIK) are:
- Call Log() in each of these methods before returning the object. I'm not a fan of this because it gets unwieldy if used on a lot of classes with a lot of methods. It also is not an intrinsic part of the method's purpose. 
- Use composition or inheritance to layer the log callon the Order class similar to: - public Customer GetCustomer() 
 {
 Customer CustomerInstance = this.originalCustomer.GetCustomer(); Log(CustomerInstance);
 return CustomerInstance;
 }
 I don't think this buys me anything over #1.
- Create extension methods on each of the returned types: - Customer CustomerInstance = Order.GetCustomer().Log(); 
 which has just as many downsides.
I'm looking to do this for every (or almost every) object returned, automatically if possible, without having to write double the amount of code. I feel like I'm either trying to bend the language into doing something it's not supposed to, or failing to recognize some language feature that would enable this. Possible solutions would be greatly appreciated.
© Stack Overflow or respective owner