C# reflection to display a struct's members with their descriptions


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

I frequently need to create a struct to be displayed in an app. The DescriptionAttribute is used to display a member's description.

Room for improvement:
* nested structs/enums
* Implement a TreeViewAble Interface


Copy this code and paste it in your HTML
  1. private struct TestStruct
  2. {
  3. #region Members to be display
  4.  
  5. [DescriptionAttribute("an integer")]
  6. public int i;
  7.  
  8. [DescriptionAttribute("a bool")]
  9. public bool b;
  10.  
  11. // no DescriptionAttribute
  12. public bool b2;
  13.  
  14. #endregion
  15.  
  16. // Example usage: myStruct.Render(treeView1.Nodes);
  17. public void Render(TreeNodeCollection arg)
  18. {
  19.  
  20. foreach (FieldInfo field in typeof(TestStruct).GetFields())
  21. {
  22.  
  23. DescriptionAttribute[] attributes = (DescriptionAttribute[])field.GetCustomAttributes(typeof(DescriptionAttribute), false);
  24. string description = attributes.Length>0 ? attributes[0].Description : field.ToString();
  25.  
  26. //AttributeCollection attributes = TypeDescriptor.GetProperties(field)[field.Name].Attributes;
  27. //DescriptionAttribute myAttribute = (DescriptionAttribute)attributes[typeof(DescriptionAttribute)];
  28.  
  29. // Show something like "My integer, 123 (Int32, i)"
  30. string s = string.Format("{0}, {1} ({2}, {3})",
  31. description, // DescriptionAttribute
  32. field.GetValue(this), // value of
  33. field.FieldType.Name,
  34. field.Name // name of structure member
  35. );
  36. arg.Add(s);
  37. }
  38. }
  39. };

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.