D.R. D.R. - 10 days ago 7
C# Question

Reflection returns backing fields of read-only properties?

It looks like Reflection returns the backing fields for properties if called like so:

type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)


Is there a way to return all fields which have been declared by the user in the class without any backing fields / compiler-generated fields / etc.?

EDIT: Is it safe to rely on the
[CompilerGenerated]
attribute?

Evk Evk
Answer

All such fields are marked with CompilerGeneratedAttribute, so you can filter like this:

var fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
            .Where(f => f.GetCustomAttribute<CompilerGeneratedAttribute>() == null).ToArray();