Nov 18, 2010

Passing the Getter and Setter of a C# Property as a Func<> and an Action<>

 

I have some automated form processing, where each control object is constructed with a getter and a setter function. I also have a wrapper to a WCF service that exposes all the services as Properties. Some of the fields need to be tied to the service Properties. For example here’s a property:

   public string SomeProperty{get;set;}

Here’s a method that returns my custom ViewControl object and takes a Func<string> and an Action<string>

   public ViewControl CreateHandler(Func<string> getFunc, Action<string> setAction)
   {
     //important stuff done here with getFunc and setAction
   }

Here’s how you get SomeProperty’s getter for getFunc and the setter for setAction using anonymous delegates:
   ViewControl the_control = CreateHandler (delegate {return SomeProperty},
                                            delegate(string value) {SomeProperty = value});

Here’s how you turn those anonymous delegates into slightly less verbose lambda expressions:

   ViewControl the_control = CreateHandler( ()=>SomeProperty, value => SomeProperty = value);

I’m sure there are other uses for getting to the underlying getter and setters and this technique should prove to be generally useful.

About Me

My photo
Tod Gentille (@todgentille) is now a Curriculum Director for Pluralsight. He's been programming professionally since well before you were born and was a software consultant for most of his career. He's also a father, husband, drummer, and windsurfer. He wants to be a guitar player but he just hasn't got the chops for it.