I would like to be able to iterate through the values of a struct in C# (.Net 2.0). This is to be done at runtime, with no knowledge of the possible values in the struct.
I was thinking along the lines of either using Reflection to add the struct values to a list, or converting the struct to a data structure that implements the IEnumerable interface. Can anyone provide any pointers?
Thanks in advance for your help.
Regards, Andy.
What exactly do you mean – the various fields within a struct? Or properties perhaps? If so,
Type.GetFields()orType.GetProperties()is the way to go.Are you absolutely sure you need to use a struct, by the way? That’s rarely the best design decision in C#, particularly if the struct contains multiple values.
EDIT: Yes, it seems that structs are being used for legacy reasons.
One thing I didn’t mention before: if the struct’s fields aren’t public, you’ll need to specify appropriate BindingFlags (e.g.
BindingFlags.Instance | BindingFlags.NonPublic).