How can I tell whether a field is the backing-field of an automatic-implemented property?



I'm using reflection to access and store properties and fields. However, to avoid having redundant data, I want to get rid of auto-implemented properties' backing fields, which are also enumerated as normal fields. Looks like these backing fields are named as "{PropertyName}k_BackingField", and it would seem that I could make do with just parsing this string, but I wonder if there's a better approach than relying on an internal, compiler-provided mangled name.


2 ответов


At least for my classes the compiler annotates those automatic property backing fields with the CompilerGenerated attribute. So you could just check for that, I think.


Well, you can check whether it's a valid C# identifier. If it isn't, that's a pretty good indicator that it's an automatic property. Indeed, if you know that it will have been compiled by a particular version of a particular compiler, you could rely on the naming pattern. Sounds a bit fragile though.

More robustly, if you just want to know whether it's compiler-generated, check whether the FieldInfo has the CompilerGeneratedAttribute applied to it. Now there are other times when the compiler will generated extra fields for you - such as for caching delegates created with lambda expressions which don't need any extra context - but it at least shows that it's not a field explicitly declared by the developer (unless they've also explicitly applied the attribute, of course).

  • Gone from two sentences to fairly elaborate in three minutes. I should have known before typing my answer. By now this one is definitely better :-)

    Joey20 октября 2009, 10:59
  • Well, at the time you answered Jon had written a couple of vague sentences I couldn’t quite understand, then you dropped the CompilerGeneratedAttribute hint and that was all I needed to know, so there you go

    Trap20 октября 2009, 13:23