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.
Could anyone provide an example how to create a structure instance at runtime? The
Share
Just use
Activator.CreateInstance(Type).Most structs don’t actually have a parameterless constructor – there’s a different form of IL used (the
initobjinstruction 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.