Adding properties in a class dynamically

Adding properties in a class dynamically

Old forum URL: forums.lhotka.net/forums/t/6693.aspx


Lalit posted on Saturday, March 28, 2009

Hi,

Can we add properties in a business base class at run time? If yes how can we do so? If possible please give me some example as well. I really am in desperate need to find a way. Any help will be great help. Thanks in advance. :)

 

-Lalit

rsbaker0 replied on Saturday, March 28, 2009

Yes, you can do this, but it's not trivial (on the other hand there are lots of examples around).

Your class type must implement the ICustomTypeDescriptor interface, and you can respond with whatever collection of properties you think is appropriate. In our case, we extend our BO's with additional custom properties added by the customer.

Google for ICustomTypeDescriptor and you'll find examples.

Note that this is not without costs. Evidently there are "bugs" in Visual Studio (and elsewhere) in which classes that implement this interface cause strange behavior. For example, in Visual Studio,  the properties of your object will no longer be visible at design time in some cases.

If I were to do this over again, (and I may still do this anyway), I would not implement this interface in the BO's themselves, but would implement a separate "wrapper" class that could contain a BO and implement ICustomTypeDescriptor to report the extended set of properties. I don't need the extra property support everywhere, mainly just in grids.

EDIT: Here's a sample on CodeProject..

http://www.codeproject.com/KB/miscctrl/bending_property.aspx

Lalit replied on Monday, March 30, 2009

Hi,

First of all thanks alot for your help. As you said that one won't need the extra property support in grids, you must have some better approach for my problem.

Actually i have a scenario where i have a class with child collections. In each screen view i need to bind the class with Infragistics UltraGrid. Here i have to show a property of items of child collection as columns, i.e. if root obejct does have 5 children in its child collection, i have to show 5 columns with other properties of root object in that grid. Its a huge object with 7 child collections containing n number of child, handling caching etc as well. It will be complex enough to handle those properties otherwise.

Approach i taken is i will design a wrapper over my business object. Now in this wrapper i will add properties at runtime depending upon no of children and bind the wrapper to the grid. There will be three different wrappers for three different views.

If you have any other simpler/better approach, i will be pleased to listen that one.

 

-Lalit

Copyright (c) Marimer LLC