Click here to Skip to main content
15,905,563 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
I am trying to add properties to a class at run time that is on the fly.
As in i want some customers email-id or phone no. but not all,or i want to add some properties on the fly.Please suggest .
Posted
Comments
nandakishoreroyal 4-Mar-14 5:51am    
Can you please post the code.
[no name] 4-Mar-14 6:09am    
Iam not getting the logic actually....if you have any idea please let me know...Thank you

1 solution

You are not going to be able to add new Properties to a Class, or an instance of the Class, at run-time with .NET; you can use Reflection.Emit and its TypeBuilder facility at run-time to create a new Class, and make it inherit from an existing Class, and then add Properties to the new Class: [^].

Please take note that if you go into this area of programming: it is very complex, and may add substantial costs to your development efforts. I strongly advise you carefully evaluate if you really need to implement this feature.

There are other alternatives you might investigate, the most relevant of which is:

1. Use of .NET's Expando object (FrameWork 4.0) in the Dynamic Language Runtime (DLR): [^], [^]. Anoop Madhusudanan has an outstanding article on CP: [^] on programming with DLR, using Expando and DynamicObject, and his own very interesting "Elastic Object.

Also check-out:

2. Code-Weaving, AOP, Aspect Oriented Programming, in which structured comments in your code are rendered into code inserted by a compile post-processor into IL: [^], [^], [^].
 
Share this answer
 
Comments
[no name] 4-Mar-14 6:58am    
Thanks a lot Bill .Will surely keep this is mind..But ya deploying this would really be complex.
BillWoodruff 4-Mar-14 13:22pm    
Do keep in mind that having a lot of Properties in a Class that are never "used" in instances of the Class ... in other words, Properties whose values are null, or some other default value ... doesn't add that much memory-use to your Application. And, at run-time, simple tests for null or default values can be used in code to determine whether or not you handle them.
[no name] 4-Mar-14 23:14pm    
Yes sure Bill.This would really help me.Can you give me some Codes using Reflection.Emit!!
BillWoodruff 5-Mar-14 0:13am    
fyi: using the words "give" and "send me" here on QA will be perceived as negative by some here. Search CodeProject for "Reflection.Emit," and study the Microsoft example I sent you a link to which does contain an example. good luck, Bill
[no name] 5-Mar-14 0:23am    
Extremely sorry Bill .New here so will surely keep in mind next...thank you

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900