Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set object property using reflection

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?

like image 875
Melursus Avatar asked Mar 06 '09 17:03

Melursus


People also ask

How do I set the properties of an object in Java?

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

What is reflection in C# with example?

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.

How do I copy values from one object to another in C#?

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.

Does C# have reflection?

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.


2 Answers

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); } 
like image 151
Andy Avatar answered Sep 16 '22 14:09

Andy


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.

like image 34
El Cheicon Avatar answered Sep 20 '22 14:09

El Cheicon