Reflection: How to get implicit struct constructor?

P

Philipp Schumann

Hi,

Using Type.GetConstructors(BindingFlags), I can't seem to be able to acquire
a ConstructorInfo object for the implicit, parameter-less constructor for a
struct if it doesn't define an explicit constructor with parameters itself.
The same apparently works for classes, though - if a class doesn't specify
any instance constructors explicitly, an implicit, public, parameterless
instance constructor is assumed and the appropriate ConstructorInfo is
returned.

Since it is possible to create a new instance of a struct that doesn't have
explicit constructors defined in code, the same should be possible using
Reflection, but what am I supposed to do without the appropriate
ConstructorInfo object?

I am aware that structs, being value types, cannot be a null reference and
thus simply declaring them will actually create them in memory, with the
"constructor" construct simply existing to provide a convenient
initialization mechanism, so this is probably why. But how would I do this
dynamically, using Reflection, just with the Type instance that's telling me
that IsValueType=true?

Cheers,
Phil
 
A

Alexander Shirshov

Phil,

I'm probably missing something here. Why do you need ConstructorInfo?

Activator.CreateInstance(type) will create an instance of your value type
using implicit parameter-less constructor.


HTH,
Alexander
 
S

sadhu

That's because a default constructor doesn't get generated for structs.

Regards
Senthil
 

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