I find it very usefull to use anonymous methods to avoid global variables
Without anonymous methods:
private static Dictionary<Binding, ErrorProvider> dict =
new Dictionary<Binding, ErrorProvider>();
public static void ParseBinding(Binding binding)
{
var errorProvider = new ErrorProvider();
dict.Add(binding, errorProvider);
binding.Parse += new ConvertEventHandler(binding_Parse);
}
static void binding_Parse(object sender, ConvertEventArgs e)
{
var binding = sender as Binding;
var errorProvider = dict[binding];
try
{
// some validation form e.Value
// throws exception if not valid
}
catch (Exception ex)
{
errorProvider.SetError(binding.Control, ex.Message);
}
}
This is really dangerous, since I need to take care for myself to remove the entries from the dictionary if not used anymore, otherwise I have a memory leak since the garbage collector will never dispose the binding or the error provider.
Now the much simpler implementation with anonymous methods:
public static void ParseBinding(Binding binding)
{
var errorProvider = new ErrorProvider();
binding.Parse += (sender, e) =>
{
try
{
// some validation form e.Value
// throws exception if not valid
}
catch (Exception ex)
{
errorProvider.SetError(binding.Control, ex.Message);
}
};
}