12.11. Filtering Output when Obtaining Members

Problem

You want to get information about one or more members, but you want to retrieve only a subset of members. For example, you need to use Type.GetConstructor to obtain only the static constructor of a type, or you need to use Type.GetField to obtain only the noninherited nonpublic fields of a type.

Solution

Use the BindingFlags enumeration together with the appropriate Type.Get xxx methods to find out about the type, as in the following example:

public static void FilteringOutputObtainingMembers( ) { Type reflection = typeof(Reflection); ConstructorInfo[] constructors = reflection.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static); Console.WriteLine("Looking for All Constructors"); foreach(ConstructorInfo c in constructors) { Console.WriteLine("\tFound Constructor {0}",c.Name); } constructors = reflection.GetConstructors(BindingFlags.Public | BindingFlags.Instance); Console.WriteLine("Looking for Public Instance Constructors"); foreach(ConstructorInfo c in constructors) { Console.WriteLine("\tFound Constructor {0}",c.Name); } constructors = reflection.GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static); Console.WriteLine("Looking for NonPublic Constructors"); foreach(ConstructorInfo c in constructors) { Console.WriteLine("\tFound Constructor {0}",c.Name); } FieldInfo[] fields = reflection.GetFields(BindingFlags.Static | BindingFlags.Public); ...

Get C# Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.