Set Property value dynamically using Reflection in C#
Hi,
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.
Console.WriteLine(age.ToString());
If you have any queries, please feel free to post it here.
try this link:
http://www.manindra.net/post/2010/04/07/C-Property-Generator-Tool.aspx