ASP.NET Weblogs

Welcome to ASP.NET Weblogs Sign in | Join | Help
in Search

The Technical Adventures of Adam Weigert

December 2007 - Posts

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

    Posted Dec 16 2007, 07:56 AM by adweigert with 5 comment(s)
    Filed under: , ,
  • C#: My First Extension Method

    I will find many, many uses for this ... maybe someone else will too!

    using System;
    using System.Diagnostics;

    internal static class StringExtensions
    {
        public static T ToEnum<T>(this string value)
            where T : struct
        {
            Debug.Assert(!string.IsNullOrEmpty(value));
            return (T)Enum.Parse(typeof(T), value, true);
        }
    }

    Posted Dec 08 2007, 10:01 AM by adweigert with 1 comment(s)
    Filed under: , ,
More Posts