Posted By

jimfred on 08/28/09


Tagged


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

umang_nine


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


 / Published in: C#
 

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

  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

Report this snippet  

You need to login to post a comment.