Could anyone provide an example how to create a structure instance at runtime? The structure I'm using doesn't define any constructors, just fields. The GetConstructor() method returns null, and so far I was unable to find a way to achieve this.
Just use Activator.CreateInstance(Type)
.
Most structs don't actually have a parameterless constructor - there's a different form of IL used (the initobj
instruction IIRC).
On the other hand, if a struct doesn't have any constructors, that suggests it's either not very useful or it's mutable - and mutable structs can cause all kinds of problems. If you're in control of the structure code yourself, I'd suggest giving it a constructor and making it immutable. There are probably cases where mutable structs are a necessary evil (particularly around interop) but they're worth avoiding if at all possible.
Have you tried using:
Object o = Activator.CreateInstance(Type t);
...or some of its other overloads?
http://msdn.microsoft.com/en-us/library/system.activator.createinstance%28v=VS.100%29.aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With