SyntaxHighlighter

Friday, 2 December 2016

Set Many Properties in One Go

If you're looking for a way to set the value of many properties who's name starts with the same string, then look no further!

Here's a useful extension you can add to an object.
public static class Extensions
{
    public static void SetPropertiesToValue(this object obj, string propertyNameStartsWith, Type propertyType, object val)
    {
        foreach (PropertyInfo prop in obj.GetType().GetProperties())
        {
            if (prop.Name.StartsWith(propertyNameStartsWith) && prop.PropertyType == propertyType && prop.CanWrite)
                prop.SetValue(obj, val);
        }
    }
}

And here's how to use it:
myObj.SetPropertiesToValue("Name", typeof(string), "Jim");
This will set any property of myObj that has a name starting with Name to Jim.