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")
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")
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.