RSS

c# Dictionary with lambda functions

03 Sep

I recently needed a quick way to allow a user to select a value from a combo box (win forms)….let me back up a bit, explain why I’m using an outdated UI technology. Isn’t everyone using the new kids on the block, javascript, jquery, angular-js, bootstrap for css and so on? Well, I am limited by the environment I am developing the app – a slow moving enterprise one.

So back to the topic at hand. A user selects a value from a combo box, and the application selects the corresponding presenter (read “controller” for MVC fans) that will manage the view.

To make my app a bit sexier and to offset the disappointment of having to use using win forms, I decided to use lambda functions in a dictionary to do the trick.

I have a setupUI method that sets up the event handler for the combo box (among other things)

    class MainPresenter
    {
      private IPresenterFactory presenterFactory;
      private IPresenter presenter;
      //....
      void SetupUI()
        {
            cbEntity.TextChanged += cbEntity_TextChange;
        }
        void cbEntity_TextChange(object sender, EventArgs e)
        {
            try
            {
                this.presenter = presenterFactory.getPresenter(cbEntity.Text);
                //.....
            }
            catch
            {
                //....
            }
        }
     }

cbEntity is the combobox 

The presenter and presenterfactory are injected into the mainpresenter elsewhere (in the main program.cs) through the constructor – not shown.
Also ItemPresenter, FormPreseneter etc… all implement Ipresenter interface
Then the succinct dictionary of lambda functions in the presenterfactory class.

class PresenterFactory:IPresenterFactory
{
  private Dictionary<string, Func<IPresenter>> presenters
    = new Dictionary<string, Func<IPresenter>>
    {
      {"Items",()=> new ItemPresenter(new ItemRepository())},
      {"Forms",()=> new FormPresenter(new FormRepository())},
      {"Synonyms",()=> new SynonymPresenter(new SynonymRepository())}

   };

public IPresenter getPresenter(string entityName)
  {
    return this.presenters[entityName]();
  }
}

So if the user selected ‘Items’ in the combo box, the dictionary lookup for the key ‘Items’, returns a a value that is a lambda function.

Then calling the lambda function with

this.presenters[entityName]();

returns the instantiated  ItemPresenter value(with dependency ‘ItemRepository’ having been injected). Same applies for different selections (Form and Synonym selections)

 
Leave a comment

Posted by on September 3, 2013 in programming, software

 

Tags: , , , , , ,

Leave a comment