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);
    }
}

5 Comments

  • Was the "!" a typo? You're throw the exception when the string is NOT empty?

  • Yes, typo, thanks. :)

  • Adam,

    I know the feeling too well, and I really think you are now suffering from from the kid-in-the-toystore syndrome ;-). Yes, .NET 3.5 is cool and so are Lamda expression but I really think you went a bit over the top by stating that

    ArgumentValidator.ThrowIf(string.IsNullOrEmpty(name), () => new ArgumentException("The parameter is required.", "name"));

    is more readable than

    if (string.IsNullOrEmpty(name)) throw new ArgumentException("The parameter is required.", "name");

    The if-version is almost plain English and readable for anyone with basic programming skills while the lamda version looks a lot more like technese ;-)

    Just my €0.05

    Joost

  • Speaking of typos, it's "Lambda", not "Lamba"

  • You picked up on my, I'm not sure about this feeling, like all new things, gotta try it out, and yes, you could argue a simple one-line IF statement is easier to read. So, one thing I discovered was I moved the IsNullOrEmpty statement to an extension method so it became the above, Validator.ThrowIf(name.IsNullOrEmpty(), () => new ArgumentNullException("name"));

    My biggest irk would be the one-line IF, I by standard always have something like that wrapped in squigglies and at minimum on four lines.

    The idea was to have something like a WriteIf method but not allocating the object unless it was needed.

Comments have been disabled for this content.