tags:

views:

1124

answers:

5

Hi,

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.

A: 

To make it work on every struct, you have to use reflection. If you want to declare a set of structs with this ability, you can make them implement IEnumerable<KeyValuePair<string, object>> and define GetEnumerator() as:

yield return new KeyValuePair<string, object>("Field1", Field1);
yield return new KeyValuePair<string, object>("Field2", Field2);
// ... and so forth
Mehrdad Afshari
A: 

Use:

Enum.GetValues(typeof(EnumType)

which returns an array of the values.

EDIT

Sorry somehow I read Enum instead of Struct. For Structs use Jon Skeets answer.

gcores
+9  A: 

What exactly do you mean - the various fields within a struct? Or properties perhaps? If so, Type.GetFields() or Type.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).

Jon Skeet
Jon,I would prefer to avoid them myself, but I'm dealing with a legacy application. Thanks for you advice.
MagicAndi
Jon, Thanks again. I was able to iterate using the following code:Type structType = typeof(MyStruct);FieldInfo[] fields = structType.GetFields();Foreach(FieldInfo field in fields) { ... }
MagicAndi
A: 

At the simplest level, assuming that you want to iterate over the properties:

PropertyInfo[] properties = myStructInstance.GetType().GetProperties();
foreach (var property in properties) {
    Console.WriteLine(property.GetValue(myStructInstance, null).ToString());
}
Jason
A: 

See the system.reflection.propertyinfo document for an example of using Reflection.

gimel