Adding a property at runtime

U

Udi

Hi All,
I have an object that is reflected at runtime by Windows script host
engine,
so its public methods and properties can then be used from within a
script.

Based on a certain condition, I need to allocate a new member inside
that object
to be able to use it through the script engine as well. (This local
member is null and ignored by default)

I was thinking about adding a property that exposes this internal
member at runtime,
so the script engine will be able to see this property while
reflecting my object.

Do you know how can I extend my class and add a new propety to it at
runtime?
Can you show me an example?
Thanks!
Udi.
 
J

Jon Skeet [C# MVP]

Do you know how can I extend my class and add a new propety to it at
runtime?
Can you show me an example?

You can't. You could use CodeDom to emit a new class derived from the
old one but including the extra property, but that's about as close as
you can get, I believe.

Jon
 
L

Larry Smith

I have an object that is reflected at runtime by Windows script host
engine,
so its public methods and properties can then be used from within a
script.

Based on a certain condition, I need to allocate a new member inside
that object
to be able to use it through the script engine as well. (This local
member is null and ignored by default)

I was thinking about adding a property that exposes this internal
member at runtime,
so the script engine will be able to see this property while
reflecting my object.

Do you know how can I extend my class and add a new propety to it at
runtime?
Can you show me an example?

Take a look at "ICustomTypeDescriptor" (which you'll inherit your class
from, requiring you to implement "GetProperties()") or in .NET 2.0 and
later, take a look at the "TypeDescriptionProviderAttribute" instead (which
requires you to roll your own "TypeDescriptionProvider" derivative,
overriding "GetTypeDescriptor()" and implementing "GetProperties()" on the
returned "ICustomTypeDescriptor" - also see class "CustomTypeDescriptor"
which you'll want to rely on here). You'll have to research the details of
course but brace yourself. It's very difficult the first time you try it.
There's also another way using the "TypeConverterAttribute" but you probably
don't need that.
 
N

Nicholas Paldino [.NET/C# MVP]

Udi,

Why not just add the property to your class, and then check your
condition before you access the property?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top