Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# struct instantiation at runtime

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.

like image 460
L.E.O Avatar asked Dec 21 '22 23:12

L.E.O


2 Answers

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.

like image 139
Jon Skeet Avatar answered Jan 02 '23 23:01

Jon Skeet


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

like image 39
Migol Avatar answered Jan 02 '23 23:01

Migol