Simple enumeration of fields of a struct in C# using reflection


/ Published in: C#
Save to your folder(s)



Copy this code and paste it in your HTML
  1. struct Employee
  2. {
  3. public string name;
  4. public int age;
  5. public string location;
  6. };
  7.  
  8. static void Main(string[] args)
  9. {
  10. Employee employee;
  11.  
  12. employee.name = "Jim Smith";
  13. employee.age = 35;
  14. employee.location = "California";
  15.  
  16. Type t = employee.GetType();
  17. System.Reflection.FieldInfo [] fields =
  18. t.GetFields(System.Reflection.BindingFlags.Instance|System.Reflection.BindingFlags.Public);
  19.  
  20. foreach (System.Reflection.FieldInfo field in fields)
  21. {
  22. Console.WriteLine(field.Name + " = " + field.GetValue(employee));
  23. }
  24.  
  25. // Expected output:
  26. // name = Jim Smith
  27. // age = 35
  28. // location = California
  29.  
  30. } // main

URL: http://www.eggheadcafe.com/conversation.aspx?messageid=29838045&threadid=29837893

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.