Wednesday, July 10, 2019

How to get or set a nested class property using C#

Summary: C# methods to set and get nested class property values.
If you need to get a set a value of a nested object property, here is a couple of functions that can help you do it using reflection (.NET 4.7, C#):
/// 
/// Gets the value of a nested object property.
/// 
/// 
/// Project that owns the property.
/// < /param>
/// 
/// Name of the property.
/// < /param>
/// 
/// Property value (or null, if property does not exists).
/// 
/// 
/// 
/// The code assumes that the property exists;
/// if it does not, the code will return null.
/// 
/// 
/// The property does not need to be nested.
/// 
/// 
/// The code handles both class properties and fields.
/// 
/// 
public static object GetPropertyValue
(
    object source, 
    string name
)
{
    if (name.Contains("."))
    {
        var names = name.Split(new char[] { '.' }, 2);

        return GetPropertyValue(GetPropertyValue(source, names[0]), names[1]);
    }
    else
    {
        PropertyInfo prop = null;

        prop = source.GetType().GetProperty(name);

        if (prop != null)
            return prop != null ? prop.GetValue(source) : null;

        FieldInfo field = source.GetType().GetField(name);

        if (field == null) return null;

        return field.GetValue(source);
    }
}

/// 
/// Sets the value of a nested object property.
/// 
/// 
/// Object that owns the property to be set. 
/// < /param>
/// 
/// Name of the property.
/// < /param>
/// 
/// Property value.
/// < /param>
/// 
/// 
/// The code assumes that the property exists;
/// if it does not, the code will do nothing.
/// 
/// 
/// The property does not need to be nested.
/// 
/// 
/// The code handles both class properties and fields.
/// 
/// 
public static void SetPropertyValue
(
    object target,
    string name, 
    object value
)
{
    var names = name.Split('.');

    for (int i = 0; i < names.Length - 1; i++)
    {
        PropertyInfo prop = target.GetType().GetProperty(names[i]);
        if (prop != null)
        {
            target = prop.GetValue(target);
            continue;
        }

        FieldInfo field = target.GetType().GetField(names[i]);
        if (field != null)
        {
            target = field.GetValue(target);
            continue;
        }

        return;
    }

    PropertyInfo targetProp = target.GetType().GetProperty(names.Last());

    if (targetProp != null)
        targetProp.SetValue(target, value);
}

No comments:

Post a Comment