C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Communities   Interview   Jobs   Projects   Offshore Development    
Silverlight Tutorials | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Revenue Sharing |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...

New Feature: Community Sites: Create your own .NET community website and start earning from Google AdSense ! It's Free !






Set Property value dynamically using Reflection in C#


Posted Date: 25 Jun 2008    Resource Type: Code Snippets    Category: Reflection
Author: Brainstorming GuyMember Level: Diamond    
Rating: Points: 10



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.




Responses


No responses found. Be the first to respond and make money from revenue sharing program.

Feedbacks      
Popular Tags   What are tags ?   Search Tags  
(No tags found.)

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: Dynamica invocation of a Method in DLL using C#
Previous Resource: Copy all control values of web page to get set properties
Return to Discussion Resource Index
Post New Resource
Category: Reflection


Post resources and earn money!
 
Related Resources



dotNet Slackers   BizTalk Adaptors    Web Design


Contact Us    Privacy Policy    Terms Of Use