title: Getting the attributes of a field using reflection in C#
body: <p>I wrote a method that extracts fields from an object like this:</p>
  
  <pre><code>private static string GetHTMLStatic(ref Object objectX, ref List&lt;string&gt; ExludeFields)
  {
      Type objectType = objectX.GetType();
      FieldInfo[] fieldInfo = objectType.GetFields();
  
      foreach (FieldInfo field in fieldInfo)
      {
          if(!ExludeFields.Contains(field.Name))
          {
              DisplayOutput += GetHTMLAttributes(field);
          }                
      }
  
      return DisplayOutput;
  }
  </code></pre>
  
  <p>Each field in my class also has it's own attributes, in this case my attribute is called HTMLAttributes. Inside the foreach loop I'm trying to get the attributes for each field and their respective values. It currently looks like this:</p>
  
  <pre><code>private static string GetHTMLAttributes(FieldInfo field)
  {
      string AttributeOutput = string.Empty;
  
      HTMLAttributes[] htmlAttributes = field.GetCustomAttributes(typeof(HTMLAttributes), false);
  
      foreach (HTMLAttributes fa in htmlAttributes)
      {
          //Do stuff with the field's attributes here.
      }
  
      return AttributeOutput;
  }
  </code></pre>
  
  <p>My attributes class looks like this:</p>
  
  <pre><code>[AttributeUsage(AttributeTargets.Field,
                  AllowMultiple = true)]
  public class HTMLAttributes : System.Attribute
  {
      public string fieldType;
      public string inputType;
  
      public HTMLAttributes(string fType, string iType)
      {
          fieldType = fType.ToString();
          inputType = iType.ToString();
      }
  }
  </code></pre>
  
  <p>This seems logical but it won't compile, I have a red squiggly line in the GetHTMLAttributes() method under:</p>
  
  <pre><code>field.GetCustomAttributes(typeof(HTMLAttributes), false);
  </code></pre>
  
  <p>The field I'm trying to extract the attributes from is in another class used like this:</p>
  
  <pre><code>[HTMLAttributes("input", "text")]
  public string CustomerName;
  </code></pre>
  
  <p>From my understanding (or lack thereof) this should work? Please expand my mind fellow developers!</p>
  
  <p><strong>*Edit, compiler error</strong>:</p>
  
  <blockquote>
    <p>Cannot implicitly convert type
    'object[]' to 'data.HTMLAttributes[]'.
    An explicit conversion exists (are you
    missing a cast?)</p>
  </blockquote>
  
  <p>I have tried casting it like this:</p>
  
  <pre><code>(HTMLAttributes)field.GetCustomAttributes(typeof(HTMLAttributes), false);
  </code></pre>
  
  <p>But that also doesn't work, I get this compiler error:</p>
  
  <blockquote>
    <p>Cannot convert type 'object[]' to
    'data.HTMLAttributes'</p>
  </blockquote>