0

How can I write extension method "SetPropValue" that it works like:

myObject.SetPropValue("Address") = "blahblah"

// which does:
myObject.Address = "blahblah"

And also "GetPropValue":

Object address = myObject.GetPropValue("Address")
2
  • Good point @LarsTech. I changed to object Commented Dec 8, 2016 at 19:05
  • There are scenarios where this is useful, for example think of a dynamic scenario where you would only know at run time what property you want to access Commented Dec 8, 2016 at 19:06

1 Answer 1

2

C# does not provide facilities for achieving the first syntax, because assignment operator does not allow overloading. You can use a more traditional syntax for the setter, though:

myObject.SetPropValue("Address", "blahblah");

Here is how you can do it:

public static void SetPropVal<T>(this object obj, string name, T val) {
    if (obj == null) return;
    obj.GetType().GetProperty(name)?.SetValue(obj, val);
}

public static T GetPropVal<T>(this object obj, string name) {
    if (obj == null) return default(T);
    var res = obj.GetType().GetProperty(name)?.GetValue(obj);
    return res != null ? (T)res : default(T);
}

Note that this approach makes sense only when string are not known at compile time, i.e. they come from a user or from configuration. When strings are known at compile time, casting to dynamic lets you achieve the same thing with a more readable syntax.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for this. The Scenario you describe where the strings come from configuration is exactly what I'm facing

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.