I’m doing some dynamic code generation using Reflection, and I’ve come across a situation where I need to get the backing field of a property (if it has one) in order to use its FieldInfo object.
Now, I know you can use
.IsDefined(typeof(CompilerGeneratedAttribute), false);
on a FieldInfo to discover whether it’s autogenerated, so I assume there’s a similar thing for Properties which auto-generate fields?
Cheers, Ed
The
get_andset_methods for properties also get theCompilerGeneratedAttributedapplied to them. While there is no strong coupling through attributes, there is a naming convention used for the backing fields of an auto property:Produces a
private string <Foo>k__BackingFieldmember (the<and>here are part of the name, as they’re legal in IL but not in C#; they have nothing to do with generics).As an example, this will get a list of all of the auto properties in a class, along with their backing fields: