Passing values to object during object instantiation using reflection, Possible?

S

Søren M. Olesen

Hi

Is it (any way) possible using reflection to set an indicator (property,
variable, attribute,..). on an object before it actually instantiated, so
that this indicator can be used in the constructor to determine how the was
created, or who created the object.. ??

TIA

Søren
 
M

Marc Gravell

Before it is instantiated, you can't do /anything/. However, you could
perhaps provide a separate constructor that is called (by reflection)
specifying this information as a parameter?

Marc
 
G

Guest

You can overload the constructor and just call them unless you have a need to
call instantiate the object via reflection (which is one of the slowest
reflection operations). Or you could (although this too is slow) inspect the
stack trace in the constructor to see who created the object.
Or you could have a static property on the object type which you can set
with information for the constructor to use. You could make this thread safe
by marking it with the ThreadStatic attribute.

I prefer the overloaded contructor option. Its the 'normal' way of coding,
the other are for if you need them for a reason.

HTH


Ciaran O'Donnell
 
S

Søren M. Olesen

Thanks guys....

I've already tried the constructor way, and it works like a charme, I was
just wondering if there was a way to implement it without adding an extra
constructor...now that I'm creating the object using reflection anyways....

BTW.

Is there a faster way then reflection to create objects dynamically based on
their type name ???
 
G

Guest

You can generate code, say as static function on a class, using the CodeDom
and compile it in memory (only in .NET2, in one it compiles to a file), then
load it as an assembly and call the function. This is faster if doing few
times but probably not for just one instantiation.
This works best if you have an interface to cast it to, other wise you will
need to reflect its methods anyway.

Ciaran O'Donnell
 

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