O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required