Reputation: 21194
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?
Upvotes: 1
Views: 553
Reputation: 101453
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();
Upvotes: 3