Seldon
Seldon

Reputation: 1425

How to add properties to the object at run-time in .net?

I'm using a 3rd party lib to do some work. I'm passing an object to the lib and it performing some actions on each property of the object. It enumerates properties using reflection. This is how it implemented and I can't change it.

I don't know which and how many properties should be processed by the lib at compile-time. This information only available at run-time. So I can't create class declaration in my source code.

It seems dynamic feature of .net4 can't help me because lib using reflection, not dynamic.

Actually I can see only two options here:

  1. Create a huge class definition like this:

    class Data
    {
        public object P1 {get; set;}
        public object P2 {get; set;}
        ....
        public object PN {get; set;}  // N should be at least 10.000
    }
    
  2. Generate class definition at runtime and use CSharpCodeProvider to compile an use it.

Can you suggest me any other options?

And sadly, I can't replace this lib with another one.

Upvotes: 4

Views: 4161

Answers (3)

Roman Pokrovskij
Roman Pokrovskij

Reputation: 9776

I guess it's about regular GUI element like Grid or PropertyGrid.

Then I would start from reflecting grid's method that accept class instance as parameter, and if it is possible fill internal Dictionary<PropertyInfo, instance> or Dictionary<Name,Value> with my own vales.

If this is impossible, instead of Emit, try to use System.CodeDom: Link

Upvotes: 1

Dan Bryant
Dan Bryant

Reputation: 27515

What you're looking for is known as a Property Bag. You may be able to implement something like this by using ICustomTypeDescriptor to expose additional metadata (assuming your library supports it).

If your consuming library is using Reflection directly (and not taking advantage of designer features like Type Descriptors) then your best bet is probably dynamic generation of a proxy wrapper with the additional properties. Castle DynamicProxy is one good way to do this.


EDIT:

Actually, I'm not sure if Castle supports adding new properties to the proxy object. You might be stuck using IL Emit directly via TypeBuilder. This is non-trivial, as you'll need to learn enough about IL Emit to generate the property accessors and there's a bit of a learning curve. That said, it's interesting and fun stuff and worth the effort if you have the time.

Upvotes: 3

alpha-mouse
alpha-mouse

Reputation: 5003

Using the first approach will lead to high memory consumption. I would have chosen use TypeBuilder class to create new types at the runtime.

Upvotes: 3

Related Questions