tad
tad

Reputation: 31

C# Modify class properties values

How could I modify all string properties of a class?

Let's say I have a model that has:

I want to add "some text" to all of the strings.

How do i make an extension method that would take the class object, grab the string values, add some text and then return the whole object with int values unchanged and string values changed?

Upvotes: 0

Views: 907

Answers (1)

Johnathan Barclay
Johnathan Barclay

Reputation: 20353

T AppendToStringProperties<T>(T obj, string toAppend)
{
    // Get all string properties defined on the object
    var stringProperties = obj
        .GetType()
        .GetProperties()
        .Where(prop => prop.PropertyType == typeof(string));

    // Append to the values
    foreach (var prop in stringProperties)
    {
        var val = (string)prop.GetValue(obj) ?? ""; // If value is null use an empty string
        val += toAppend;
        prop.SetValue(obj, val);
    }

    return obj;
}

Upvotes: 1

Related Questions