A Generic GetProperty

Bill from VisibleReality.com shipped me a generic version of the code that I forgot initially on my prior post. Here it is.

 

You need to include:

Code Snippet
  1. using System;
  2. using System.ComponentModel;

The code

Code Snippet
  1. /// <summary>
  2.     /// Gets the property value.
  3.     /// </summary>
  4.     /// <typeparam name="T">The type of the property value to get.</typeparam>
  5.     /// <param name="dataItem">The data item.</param>
  6.     /// <param name="field">The field.</param>
  7.     /// <param name="defaultValue">The default value.</param>
  8.     /// <returns>The property value.</returns>
  9.     public static T GetProperty<T>(this object dataItem, string field, T defaultValue = default(T))
  10.     {
  11.       if (dataItem == null)
  12.       {
  13.         throw new ArgumentNullException("dataItem");
  14.       }
  15.  
  16.       if (string.IsNullOrWhiteSpace(field))
  17.       {
  18.         return defaultValue;
  19.       }
  20.  
  21.       var props = TypeDescriptor.GetProperties(dataItem);
  22.       if (props.Count > 0)
  23.       {
  24.         if (props[field] != null && null != props[field].GetValue(dataItem))
  25.         {
  26.           return (T)props[field].GetValue(dataItem);
  27.         }
  28.  
  29.         for (var i = 0; i < props.Count; i++)
  30.         {
  31.           if (string.Compare(props[i].Name, field, StringComparison.OrdinalIgnoreCase) == 0)
  32.           {
  33.             return (T)props[i].GetValue(dataItem);
  34.           }
  35.         }
  36.       }
  37.  
  38.       return default(T);
  39.     }

Comments

Popular posts from this blog

Yet once more into the breech (of altered programming logic)

Simple WP7 Mango App for Background Tasks, Toast, and Tiles: Code Explanation

How to convert SVG data to a Png Image file Using InkScape