D.R.
D.R.

Reputation: 21194

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?

Upvotes: 1

Views: 553

Answers (1)

Evk
Evk

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

Related Questions