Return to Snippet

Revision: 17256
at August 28, 2009 18:06 by jimfred


Initial Code
private struct TestStruct
{
   #region Members to be display

   [DescriptionAttribute("an integer")]
   public int i;

   [DescriptionAttribute("a bool")]
   public bool b;

   // no DescriptionAttribute
   public bool b2;

   #endregion 

   // Example usage: myStruct.Render(treeView1.Nodes);
   public void Render(TreeNodeCollection arg)
   {

      foreach (FieldInfo field in typeof(TestStruct).GetFields())
      {

         DescriptionAttribute[] attributes = (DescriptionAttribute[])field.GetCustomAttributes(typeof(DescriptionAttribute), false);
         string description = attributes.Length>0 ? attributes[0].Description : field.ToString();

         //AttributeCollection attributes = TypeDescriptor.GetProperties(field)[field.Name].Attributes;
         //DescriptionAttribute myAttribute = (DescriptionAttribute)attributes[typeof(DescriptionAttribute)];

         // Show something like "My integer, 123 (Int32, i)"
         string s = string.Format("{0}, {1}  ({2}, {3})",
            description,          // DescriptionAttribute
            field.GetValue(this), // value of
            field.FieldType.Name,
            field.Name // name of structure member
         );
         arg.Add(s);
      }
   }
};

Initial URL

                                

Initial Description
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

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

Initial Tags

                                

Initial Language
C#