How to create Struct with Reflection


It turns out struct don’t expose their default constructor with typeof(MyStruct).GetTypeInfo().DeclaredConstructor
How do I create a struct with reflection then?
trying to port my serializer to .NET core…
On full .NET I was using System.Runtime.Serialization.FormatterServices.GetUninitializedObject(type)
but it is unavailable to .NET core…


Never mind found it!!!
I had some code somewhere already doing it with reflection! :slight_smile:


Would be great if you could add a link or a piece of sample code demonstrating that solution for any future person looking for that answer. :slight_smile:


It’s still me (not sure how I logged in initially haha!)
Anyway, here it is:


Can’t you just use Activator? I.e. Activator.CreateInstance<MyStruct>() or Activator.CreateInstance(typeof(MyStruct)).


it is slower…
I am not using Emit here to merely solve the problem, but mostly for performance reason…

(this is part of a broader effort in my serializer to improve performance, this is not the only method that use Emit)
And it worked! With judicious use of Emit I cut down my serialization time by 10 (i.e. it’s 10 times faster! i.e. it run in 10% of the time without reflection)

.NET Foundation Website | Blog | Projects | Code of Conduct