C# - Enumerating Custom Attributes via Reflection
<p>Here is my attribute definition:</p>

<pre><code>[AttributeUsage(AttributeTargets.Field)]
public class Optional : System.Attribute
{
    public Optional()
    {
    }
}
</code></pre>

<p>In MyClass:</p>

<pre><code>[Optional] public TextBox Name;
</code></pre>

<p>Finally in another function:</p>

<pre><code>typeof(MyClass).GetFields().ToList&lt;FieldInfo&gt;().ForEach(x =&gt; writer.WriteLine(
   x.FieldType + " is called " + 
   x.Name + " and has attributes " + 
   x.GetCustomAttributes(true)[0]
 ));
</code></pre>

<p>The problem is I get an error for index 0. I just want to check for fields where the attribute is applied. The error goes away when I remove <code>x.GetCustomAttributes(true)[0]</code>.</p>

<p>Exact Error:</p>

<p><strong>Exception Details: System.IndexOutOfRangeException: Index was outside the bounds of the array.</strong></p>

<p>Source Error: </p>

<pre><code>Line 63:             }
Line 64: 
Line 65:             typeof(T).GetFields().ToList&lt;FieldInfo&gt;().ForEach(x =&gt; writer.WriteLine(x.FieldType + " is called " + 
Line 66:                 x.Name + " and has attributes " + 
Line 67:                 x.GetCustomAttributes(true)[0]+ "&lt;/br&gt;"));
</code></pre>
