There are two main problems here. The first is with your use of the field's DeclaringType
property instead of its Type
property. DeclaringType
refers to the type in which the field is declared, which doesn't seem to be what you want to examine. For example, in
public class Foo
{
private Bar _bar;
}
_bar
's DeclaringType
is Foo
, but its Type
is Bar
.
Unfortunately, fixing this won't resolve the bigger problem, which is that StructLayoutAttribute
is a special attribute that doesn't actually make it into the generated IL as a custom attribute. The compiled struct will always be marked as having a sequential, explicit, or auto layout, but this is done using the type header, not by conserving the StructLayoutAttribute
in the IL. If the source code did not include a StructLayoutAttribute
, the compiled struct will be marked as having a sequential layout.
What this ultimately means for your rule is that it can't be written against the IL unless what you actually care about is the kind of layout as opposed to the presence of the attribute. If the presence of the attribute really is relevant to you, a tool that examines the source code (e.g.: StyleCop) would be a more suitable choice.