WYSIWYG

http://kufli.blogspot.com
http://github.com/karthik20522

Saturday, June 2, 2012

Code Snippets - June 2012 Edition

I keep coming across scenarios where I need to check if an Object is truly empty and not just NULL. Part of the solution was to do perform conditional checks (if-then-else) on every property but it turned out to be very manual, high maintenance and time consuming work. Following is a quick and dirty way to check if a class is truly empty:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/// <summary>
/// var isEmpty = IsObjectEmpty(someObject);
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static bool IsObjectEmpty(object obj)
{
    if (obj == null)
        return true;
 
    List<string> values = obj.GetType().GetProperties()
                          .Select(prop => prop.GetValue(obj, null))
                          .Where(val => val != null)
                          .Select(val => val.ToString())
                          .Where(str => str.Length > 0 && !str.Equals("0"))
                          .ToList();
 
    return values.Count == 0;
}


One of the most annoying part of statically typed programming language is the problem of NULL exceptions. Again "if-the-else" was the initial solution and following is a dynamic way of handling NULL values of any type. The following code takes in any property of an object (the object can be NULL by itself) and if the property is NULL it would spit out the default value that was provided.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/// <summary>
/// using System.Linq.Expressions;
///
/// Examples:
///     var value = PrintProperty(() => Object.PropertyName, "-");
///     var value = PrintProperty(() => Object.Status, "I").Equals("A") ? "Active" : "Inactive";
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="e"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
public static object PrintProperty<T>(Expression<Func<T>> e, object defaultValue)
{
    if (e == null)
        return defaultValue;
    try
    {
        T value = e.Compile()();
        return value as object ?? defaultValue;
    }
    catch { }
 
    return defaultValue;
}

Labels: ,