Is there a way in C# where I can use reflection to set an object property?
Ex:
MyObject obj = new MyObject(); obj.Name = 'Value';
I want to set obj.Name with reflection. Something like:
Reflection.SetProperty(obj, 'Name') = 'Value';
Is there a way of doing this?
Yes, you can use
Type.InvokeMember():This will throw an exception if
objdoesn’t have a property calledName, or it can’t be set.Another approach is to get the metadata for the property, and then set it. This will allow you to check for the existence of the property, and verify that it can be set: