So, I've been getting to grips with using Lambda functions instead of creating simple methods that only include one line.
The main driver behind this is the fact that I'm trying to make my code readable (using StyleCop has helped with this, and I'm sure I'll blog about that too) so I can tell others what I expect.
This area is something that's always been alien to me, and I only knew they existed last year when the .NET guru at my previous company introduced me.
Now the code I've used it in previously looked like this...
var settings = new XmlReaderSettings
{
ValidationType = ValidationType.Schema,
Schemas = xss
};
settings.ValidationEventHandler +=
new ValidationEventHandler(this.settings_ValidationEventHandler);
...
private void settings_ValidationEventHandler(object sender,
ValidationEventArgs e)
{
this.validationErrors.Add(e);
}
This seems to be a pointless method in my opinion, the only advantage is a hypothetical benefit that I may want to reuse it. For the purpose of this code, I won't ever need that.
So I've changed it to this...
var settings = new XmlReaderSettings
{
ValidationType = ValidationType.Schema,
Schemas = xss
};
settings.ValidationEventHandler +=
(s, e) => this.validationErrors.Add(e);
It's simple really.
To explain (in my own humble way that's probably wrong)...
If something is expecting a delegate function, starting it with "()
" means that you're writing a function in line. If the function needs parameters, you give the parameters a name by adding them in the order they need to be (in this case, the first is an object, normally called "sender
" when using autogenerated methods, the second is the args
, normally called "e
"). So you end up with (s, e)
.
Then you used the "=>
" (pronounced "in to"), and then the action(s) you want to run.
So there you have it, a simple use for a new(ish) feature in .NET. Makes code reading simpler, reduces non-sense methods.
One downside in doing it this way is that you can't remove the handler without disposing of the object (settings) completely and starting again.