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
- using System;
- using System.ComponentModel;
The code
Code Snippet
- /// <summary>
- /// Gets the property value.
- /// </summary>
- /// <typeparam name="T">The type of the property value to get.</typeparam>
- /// <param name="dataItem">The data item.</param>
- /// <param name="field">The field.</param>
- /// <param name="defaultValue">The default value.</param>
- /// <returns>The property value.</returns>
- public static T GetProperty<T>(this object dataItem, string field, T defaultValue = default(T))
- {
- if (dataItem == null)
- {
- throw new ArgumentNullException("dataItem");
- }
- if (string.IsNullOrWhiteSpace(field))
- {
- return defaultValue;
- }
- var props = TypeDescriptor.GetProperties(dataItem);
- if (props.Count > 0)
- {
- if (props[field] != null && null != props[field].GetValue(dataItem))
- {
- return (T)props[field].GetValue(dataItem);
- }
- for (var i = 0; i < props.Count; i++)
- {
- if (string.Compare(props[i].Name, field, StringComparison.OrdinalIgnoreCase) == 0)
- {
- return (T)props[i].GetValue(dataItem);
- }
- }
- }
- return default(T);
- }
Comments
Post a Comment