Loop Through Struct in C#

Posted by Matt Johnson | 2008-06-02 16:45:18

So here we have a home struct:

public struct home { public string homeID; public int member_cnt; public double yearly_income; public string state; }

and in some other code we create a var based on that struct:

home my_home; my_home.homeID = "123A"; my_home.member_cnt = 5; my_home.yearly_income = 50000; my_home.state = "WA";

Now we want to write a foreach loop that jumps through each property of the struct. First we create an array of all the elements in the struct with this crazy line of code (I'm not going to explain it, because I don't really know how it works):

System.Reflection.FieldInfo[] fields = my_home.GetType().GetFields(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);

The fields array is setup with all the elements of the struct, so now we can loop through them:

foreach (System.Reflection.FieldInfo field in fields) { MessageBox.Show(field.GetValue(my_home).ToString()); }

There ya go. Hopefully you'll find that useful.