Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if FieldInfo is compiler generated backingfield

Tags:

c#

reflection

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)

like image 784
Steffen Avatar asked Jan 23 '23 06:01

Steffen


1 Answers

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

like image 99
Marc Gravell Avatar answered Jan 24 '23 18:01

Marc Gravell