Skip to content

Instantly share code, notes, and snippets.

@Larry57
Last active October 21, 2015 06:03
Show Gist options
  • Save Larry57/648a9659cc885c32d5b6 to your computer and use it in GitHub Desktop.
Save Larry57/648a9659cc885c32d5b6 to your computer and use it in GitHub Desktop.
Get and Set properties values using a path with dots ("user.address.street"...)
using System.Reflection;
namespace System
{
internal static class ObjectExtensions
{
public static PropertyInfo GetPropertyInfo(this Type type, string name)
{
string[] bits = name.Split('.');
for (int i = 0; i < bits.Length - 1; i++)
type = type.GetProperty(bits[i]).PropertyType;
return type.GetProperty(bits[bits.Length - 1]);
}
public static void SetPropertyValue(this object target, string name, object value)
{
var bits = name.Split('.');
for (int i = 0; i < bits.Length - 1; i++)
target = target.GetType().GetProperty(bits[i]).GetValue(target, null);
var propertyToSet = target.GetType().GetProperty(bits[bits.Length - 1]);
if (propertyToSet == null)
throw new ArgumentException(string.Format("Bad property name {0}", name));
if (value == null)
if (propertyToSet.PropertyType == typeof(string)) // http://stackoverflow.com/questions/2092530/how-do-i-use-activator-createinstance-with-strings
propertyToSet.SetValue(target, (string)null, null);
else
propertyToSet.SetValue(target, Activator.CreateInstance(propertyToSet.PropertyType), null);
else
propertyToSet.SetValue(target, value, null);
}
public static T GetPropertyValue<T>(this object source, string name)
{
if (source == null)
throw new ArgumentNullException();
var bits = name.Split('.');
for (int i = 0; i < bits.Length - 1; i++)
source = source.GetType().GetProperty(bits[i]).GetValue(source, null);
var propertyToGet = source.GetType().GetProperty(bits[bits.Length - 1]);
if (propertyToGet == null)
throw new ArgumentException(string.Format("Bad property name {0}", name));
return (T)propertyToGet.GetValue(source, null);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment