Sunday, March 6, 2011

LINQ To LDAP: String to Int follow-up

I said I would clean up my DelegateBuilder class when I could. Here's the updated version that now even supports enum mapping. A lot cleaner in my opinion.
private static readonly Func<object, Type, object> ConvertStringToValueTypeIfNecessaryFunction =
    (o, t) =>
        {
            string str;
            if ((str = o as string) != null && t.IsValueType)
            {
                if (t.IsGenericType && string.Empty.Equals(str))
                {
                    return null;
                }

                return t.IsEnum 
                    ? Enum.Parse(t, str, true) 
                    : Convert.ChangeType(str, t);
            }
            return o;
        };