Skip to content

Instantly share code, notes, and snippets.

@AdamLJohnson
Last active February 29, 2016 18:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AdamLJohnson/0a9e73c2e7de3df49711 to your computer and use it in GitHub Desktop.
Save AdamLJohnson/0a9e73c2e7de3df49711 to your computer and use it in GitHub Desktop.
Recursive SetProperty
using System;
using System.Linq;
using System.Reflection;
public class RecursiveSetProperty
{
/// <summary>
/// Sets the property of an object recursively.
/// </summary>
/// <param name="target">The target object.</param>
/// <param name="field">The field.</param>
/// <param name="value">The value.</param>
public static void SetProperty(object target, string field, object value)
{
string[] bits = field.Split('.');
if (bits.Length == 1)
{
PropertyInfo prop = target.GetType().GetProperty(bits[0]);
if (prop != null)
prop.SetValue(target, value);
}
else
{
PropertyInfo propertyToGet = target.GetType().GetProperty(bits[0]);
if (propertyToGet != null)
{
var obj = propertyToGet.GetValue(target, null);
SetProperty(obj, string.Join(".", bits.Skip(1)), value);
}
}
}
public static void Main()
{
var testObj = new Level();
SetProperty(testObj, "Text", "Hello One");
SetProperty(testObj, "NextLevel", new Level());
SetProperty(testObj, "NextLevel.Text", "Hello Two");
SetProperty(testObj, "NextLevel.NextLevel", new Level());
SetProperty(testObj, "NextLevel.NextLevel.Text", "Hello Three");
Console.WriteLine(testObj.Text);
Console.WriteLine(testObj.NextLevel.Text);
Console.WriteLine(testObj.NextLevel.NextLevel.Text);
}
}
public class Level
{
public string Text {get; set;}
public Level NextLevel {get; set;}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment