Set Property value dynamically using Reflection in C#

In this code snippet, we are going to look how to set a property value dynamically using C#. Create a class library with the following code. Compile this as well.

namespace MyClassLibrary
public class ReflectionClass
private int _age;

public int Age
get { return _age; }
set { _age = value; }

Create a console application and in the debug folder of this application copy the DLL which was created by previous project. Then put the following code.
Here, we are going to set the value to the property Age and we are going to get it back.

// will load the assembly
Assembly myAssembly = Assembly.LoadFile(Environment.CurrentDirectory + "\\MyClassLibrary.dll");
// get the class. Always give fully qualified name.
Type ReflectionObject = myAssembly.GetType("MyClassLibrary.ReflectionClass");
// create an instance of the class
object classObject = Activator.CreateInstance(ReflectionObject);
// set the property of Age to 10. last parameter null is for index. If you want to send any value for collection type
// then you can specify the index here. Here we are not using the collection. So we pass it as null
ReflectionObject.GetProperty("Age").SetValue(classObject, 10,null);
// get the value from the property Age which we set it in our previous example
object age = ReflectionObject.GetProperty("Age").GetValue(classObject,null);
// write the age.

If you have any queries, please feel free to post it here.


Author: Manindra Kumar Upadhyay07 Apr 2010 Member Level: Gold   Points : 1

try this link:

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: