C#: My First Lambda Expression
I don't know about anyone else, but I found it annoying to have to put on three-lines of code (or one ugly one-line of code) for an IF statement for argument validation. Mostly, I want to check a simple condition and if true, throw an exception. Well, lambda to the rescue! I find the lambda version much more readable than a one-line IF statement, but that is just me -- mainly because I dislike one-line IF statements.
Another advantage of the lamba expression is that the "new Exception" is only created if the delegate is called when the condition is true. Who knows, maybe I'll change my mind on liking this after I have more experience with .NET 3.5, but for now I think this is very cool...
I guess this will have to do until we have MACRO replacement in C# ... :)
public
delegate T
CreateObjectDelegate<T>();
internal
static
class
Validator
{
public
static
void ThrowIf(bool
condition,
CreateObjectDelegate<Exception> createObject)
{
if (condition)
{
throw
createObject();
}
}
}
internal
static
class
Example
{
static
void ShowName(string
name)
{
// LAMBA expression
Validator.ThrowIf(name.IsNullOrEmpty(), () =>
new
ArgumentException("The parameter is required.",
"name"));
// IF statement
if (name.IsNullOrEmpty())
throw
new
ArgumentException("The parameter is required.",
"name");
Console.WriteLine(name);
}
}