Determine if FieldInfo will be a compiler generated

The name pretty much says it all, how do I know if I get the compiler created by backingfield for {get; set;} property?

I run 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 find that FieldInfo is a background field without relying on checking its name? (Which is quite undocumented and could be broken in the next version of the framework)

+3
source share
1 answer

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

+7
source

Source: https://habr.com/ru/post/1741114/


All Articles