By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,720 Members | 2,095 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,720 IT Pros & Developers. It's quick & easy.

How to dynamically add propery in a Class in C#?

P: 3
Hi All,

I need to create property in a class dynamically.
Property names will come from database and also the total number of properies can be changed according to database value.
I have tried with CodeDome,but unable to solve.
Please suggest me.
Dec 23 '08 #1
Share this Question
Share on Google+
3 Replies


Plater
Expert 5K+
P: 7,872
I think you might be able to do this with Reflection, but I've not done it myself.
Assuming that you want this to be built at run time, you will never be able to write in your code myobject.SomeDataBaseProperty.

It would be very easy to have it work like myobject.GetProperty("SomePropertyName")
Dec 23 '08 #2

Expert 100+
P: 190
Have a look at the System.Reflection.Emit namespace, particularly the PropertyBuilder class.

However, I can firmly suggest that this is not the preferred solution from a design standpoint. Are you building a business application? If so, you need to take maintainability, readability and flexibility into account. Using Reflection to dynamically emit code to solve a business problem gets very low marks on the first two (maintainability, readability).

Another approach you might consider is the concept of a "PropertyBag." There is an actual class with this name related to Web classes, but you don't need to use that class to implement the concept. Basically, you associate a Dictionary with your class. The Key is the PropertyName and the Value is the PropertyValue. You can have a flexible number of properties with names created at runtime. You can then write one or two functions or indexers which allows you to retrieve the property value by name after looking it up in the Dictionary.

A third option would be to implement the "PropertyBag" concept using an Xml Document or Node. You could pull the properties and values directly from the database. Each element would be a property. You could add attributes describing the property type and legitimate values (similar to an xml schema document). And again, write a method which traverses the document and looks up properties based on name.
Dec 23 '08 #3

P: n/a
With .Net 4.0 you can create anonymous classes and create propertyName = value in the declaration of the anonymous class. LINQ to SQL does this.
Nov 16 '10 #4

Post your reply

Sign in to post your reply or Sign up for a free account.