I know the name of a property in my C# class. Is it possible to use reflection to set the value of this property?
For example, say I know the name of a property is string propertyName = "first_name";
. And there actaully exists a property called first_name
. Can I set it using this string?
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.
The get method returns the value of the variable name . The set method assigns a value to the name variable. The value keyword represents the value we assign to the property. If you don't fully understand it, take a look at the example below.
Yes, you can use reflection - just fetch it with Type.GetProperty
(specifying binding flags if necessary), then call SetValue
appropriately. Sample:
using System; class Person { public string Name { get; set; } } class Test { static void Main(string[] arg) { Person p = new Person(); var property = typeof(Person).GetProperty("Name"); property.SetValue(p, "Jon", null); Console.WriteLine(p.Name); // Jon } }
If it's not a public property, you'll need to specify BindingFlags.NonPublic | BindingFlags.Instance
in the GetProperty
call.
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