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?
You can set properties at object initialization by providing property-value pairs in a call to the object's Init method: Obj = OBJ_NEW('ObjectClass', PROPERTY = value, ... )
Reflection provides objects (of type Type) that describe assemblies, modules, and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties.
In general, when we try to copy one object to another object, both the objects will share the same memory address. Normally, we use assignment operator, = , to copy the reference, not the object except when there is value type field. This operator will always copy the reference, not the actual object.
Reflection in C# is used to retrieve metadata on types at runtime. In other words, you can use reflection to inspect metadata of the types in your program dynamically -- you can retrieve information on the loaded assemblies and the types defined in them.
Yes, you can use Type.InvokeMember()
:
using System.Reflection; MyObject obj = new MyObject(); obj.GetType().InvokeMember("Name", BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty, Type.DefaultBinder, obj, "Value");
This will throw an exception if obj
doesn't have a property called Name
, 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:
using System.Reflection; MyObject obj = new MyObject(); PropertyInfo prop = obj.GetType().GetProperty("Name", BindingFlags.Public | BindingFlags.Instance); if(null != prop && prop.CanWrite) { prop.SetValue(obj, "Value", null); }
You can also do:
Type type = target.GetType(); PropertyInfo prop = type.GetProperty("propertyName"); prop.SetValue (target, propertyValue, null);
where target is the object that will have its property set.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With