0

How could I modify all string properties of a class?

Let's say I have a model that has:

  • 2 x int properties
  • 10 x string properties

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?

4
  • 2
    You'd need reflection. I'd start learning about it here: learn.microsoft.com/en-us/dotnet/framework/… Commented Sep 16, 2021 at 10:15
  • Use reflection. Commented Sep 16, 2021 at 10:22
  • 1
    I would say most likely your design is wrong. Could you explain why you want to do something like that ? If you really need to add something to all strings they should be in an Array. Commented Sep 16, 2021 at 11:05
  • I used the question as an example. What I really need is to html encode each string from a class I receive as a request in my endpoint. I need it so that if someone tries to inject html code like <br>, it needs to get converted to &lt;brgt; Commented Sep 16, 2021 at 11:46

1 Answer 1

1
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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.