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.
+5
A:
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.
Jon Skeet
2010-09-20 12:38:30
Thanks. I've heard about mutable structs sometimes creating confusion, but never knew exactly when and why such problems occur. Guess its time to find out.
L.E.O
2010-09-20 12:56:46
@L.E.O.: It's things like fetching a value, then changing a field within that value, and it not being reflected in the original place you fetched it from. All kinds of weird effects, basically.
Jon Skeet
2010-09-20 12:58:02
+5
A:
Have you tried using
Object o = Activator.CreateInstance(Type t);
or some other of it overloads?
http://msdn.microsoft.com/en-us/library/system.activator.createinstance%28v=VS.100%29.aspx
Migol
2010-09-20 12:38:50