2

I am trying to define a struct dynamically in C#, based on a given input file with a list of member names and types. For the sake of the question, assume the file has the following layout:


[Struct Name 1]
parameter1, type1, typical_value1
parameter2, type2
parameter3, type1

[Struct Name 2]
  ... etc

I have been reading through this post for some time now, and have not yet implemented it in C# -- my question is, can this be done? Furthermore, can it be done without using unsafe?

The reason I originally wanted to stick with using a struct is because I'm going to be using it to serialize a byte[] received via I/O, and the extension methods I have right now work perfectly for statically defined structs; however I would be open to rewriting it for a wrapper class to make it easier.

The idea is that I would have one of several files that can be selected as a parsing source, based on what the user knows to be connected via I/O. In other words, the file can be changed during runtime but only a single file can be selected at a time.

Community
  • 1
  • 1
Forest Kunecke
  • 2,160
  • 15
  • 32

1 Answers1

4

Yes, technically it can be done - but not in a very useful way. You would have to use TypeBuilder to create the type at runtime (which is pretty complicated), but the next problem is that it is very hard to talk to types known only at runtime. Usually this is done via either object or an interface - but both of these would require boxing the struct, making it not very useful to be a struct in the first place. The only workaround to that is generics via T (which can then use the "constrained" model to avoid boxing) - you would need a method like:

Foo<T>(T data);

or

Foo<T>(T[] data);

that you switch into via methodInfo.MakeGenericMethod(...).Invoke(...).

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900