Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I set a property value with Reflection?

Tags:

c#

reflection

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?

like image 918
user489041 Avatar asked Oct 10 '11 21:10

user489041


People also ask

What is C# reflection?

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.

What is get set in C#?

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.


1 Answers

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.

like image 129
Jon Skeet Avatar answered Sep 23 '22 21:09

Jon Skeet