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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With