Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

BindingFlags — filtering members with reflection

BindingFlags controls which type members reflection searches for. Combine visibility and member-kind flags with |, and use DeclaredOnly to exclude inherited members.

Version: .NET 10; repository net10.0 and LangVersion=preview; feature versions require per-entry verification

Syntax

typeof(T).GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly)

BindingFlags is a flags enumeration in System.Reflection, used by APIs such as Type.GetFields. Combine values with the bitwise | operator, not &. This is a .NET library API, not a language feature requiring LangVersion=preview; the example targets net10.0.

BindingFlags.Public selects public members. BindingFlags.Instance includes members associated with an object, while BindingFlags.Static includes static members. In a GetFields(flags) call, supply at least one visibility flag (Public or NonPublic) and at least one member-kind flag (Instance or Static); otherwise, the result is empty. You can combine both member kinds.

BindingFlags.DeclaredOnly restricts the search to members declared directly on the inspected type, excluding inherited members. It does not replace the other filters. Without this flag, GetFields can return inherited instance fields; including public and protected static fields from base classes requires BindingFlags.FlattenHierarchy. Private static fields from base classes are not returned even then.

The example searches for public instance and static fields on Derived, then repeats the search with DeclaredOnly. The BaseValue field disappears, while private Hidden appears in neither result. Names are explicitly sorted using StringComparer.Ordinal so that the output does not depend on metadata order.

Examples

using System;
using System.Reflection;

BindingFlags flags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static;
PrintFields(flags);
PrintFields(flags | BindingFlags.DeclaredOnly);

static void PrintFields(BindingFlags flags)
{
    FieldInfo[] fields = typeof(Derived).GetFields(flags);
    string[] names = Array.ConvertAll(fields, field => field.Name);
    Array.Sort(names, StringComparer.Ordinal);
    Console.WriteLine(string.Join(", ", names));
}

class Base
{
    public int BaseValue = 1;
}

class Derived : Base
{
    public static int Count = 2;
    public string Name = "demo";
    private int Hidden = 3;
}

Result

BaseValue, Count, Name
Count, Name

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources