4

The title pretty much says it all, how do I know if I'm getting a compiler generated backingfield for a {get; set;} property ?

I'm running this code to get my FieldInfos:

Class MyType
{
    private int foo;
    public int bar {get; private set; }
}

Type type = TypeOf(MyType);
foreach (FieldInfo fi in type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.NonPublic))
{
    // Gets both foo and bar, however bar is called <bar>k__backingfield.
}

so the question is, can I somehow detect that the FieldInfo is a backingfield, without relying on checking its name ? (Which is pretty undocumented, and could be broken in next version of the framework)

Steffen
  • 13,648
  • 7
  • 57
  • 67
  • Why do you need to know, out of curiosity? (it might affect the answer) – Marc Gravell Apr 14 '10 at 15:54
  • Well it's because I grab all FieldInfo and PropertyInfo of a specific type and store them in a dictionary. I use it for a reflection based ORM (which I believe you sent me some dynamic code for once) Anyway I'm pretty certain GetCustomAttributes will do the trick :-) – Steffen Apr 14 '10 at 15:59

1 Answers1

9

Check .IsDefined(typeof(CompilerGeneratedAttribute), false); on them.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900