Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 905
Trap Avatar asked Dec 10 '22 19:12

Trap


2 Answers

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.

like image 187
Joey Avatar answered Jan 18 '23 22:01

Joey


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

like image 36
Jon Skeet Avatar answered Jan 18 '23 23:01

Jon Skeet