Skip to content

Instantly share code, notes, and snippets.

@draganjovanovic1
Last active March 11, 2019 17:39
Show Gist options
  • Save draganjovanovic1/5701262 to your computer and use it in GitHub Desktop.
Save draganjovanovic1/5701262 to your computer and use it in GitHub Desktop.
Generic object extension for reading - setting property values to - from key value pairs....
/// <summary>
/// Generic extension.
/// </summary>
public static class GenericExtension
{
/// <summary>
/// Read properties to key-value pair.
/// </summary>
/// <typeparam name="T">Class type.</typeparam>
/// <param name="obj">Object instance.</param>
/// <returns>Property name - value pairs.</returns>
public static IEnumerable<KeyValuePair<string, object>> GetObjectProperties<T>(this T obj)
where T : class
{
foreach (var pi in obj.GetType().GetProperties())
{
var prop = obj.GetType().GetProperty(pi.Name);
object value = prop.PropertyType.IsEnum ? prop.GetValue(obj).ToString() : prop.GetValue(obj);
yield return new KeyValuePair<string, object>
(pi.Name, value);
}
}
/// <summary>
/// Set properties.
/// </summary>
/// <typeparam name="T">Class type.</typeparam>
/// <param name="obj">Object instance.</param>
/// <param name="properties">Set properties from key - value pairs.</param>
public static void SetObjectProperties<T>(this T obj, IEnumerable<KeyValuePair<string, object>> properties)
where T : class
{
foreach (var prop in properties)
SetObjectProperty(obj, prop.Key, prop.Value);
}
/// <summary>
/// Set property value.
/// </summary>
/// <typeparam name="T">Class type.</typeparam>
/// <param name="obj">Object instance.</param>
/// <param name="property">Property name.</param>
/// <param name="value">Value.</param>
public static void SetObjectProperty<T>(this T obj, string property, object value)
where T : class
{
var pi = obj.GetType().GetProperty(property);
if (pi != null && pi.CanWrite)
{
var type = pi.PropertyType;
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
var nullType = Nullable.GetUnderlyingType(type);
if (nullType.IsEnum)
pi.SetValue(obj, Convert.ChangeType(Enum.ToObject(nullType, value), nullType), null);
else
pi.SetValue(obj, Convert.ChangeType(value, nullType), null);
}
else
{
if (type.IsEnum)
pi.SetValue(obj, Enum.ToObject(type, value), null);
else
pi.SetValue(obj, value, null);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment