Trap
Trap

Reputation: 63

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.

Thanks.

Upvotes: 6

Views: 1225

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1499770

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).

Upvotes: 7

Joey
Joey

Reputation: 354356

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.

Upvotes: 11

Related Questions