Fog Creek Software
Discussion Board

Welcome! and rules

Joel on Software

Reflection andthe parameterless struct constructor

I am trying to construct a boxed struct with reflection. I expected something like this to work (where type is the type of the struct):

ConstructorInfo info = type.GetConstructor(new Type[0]);
object obj = info.Invoke(new object[0]);

This doesn't work; info is a null reference. I've tried type.TypeInitializer instead, but it's also null. I've tried iterating through all the constructors with type.GetConstructors() and a foreach statement, but it only shows constructors with parameters.

I'd rather not do something crude like taking an arbitrary constructor and feeding it default values for each argument, but if I have to, I can.  I'm using VS .NET 2002 (and therefore the version 1.0 of the .NET Framework) if that makes any difference.

Thursday, October 14, 2004

I should add that I am trying to do this so that I can then call obj.GetType(), after which I will iterate through and assign to the fields of the struct.  Maybe there's a better way to do it.

Thursday, October 14, 2004

Figured it out: Activator.CreateInstance() is what I was looking for.

Thursday, October 14, 2004

*  Recent Topics

*  Fog Creek Home