BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Reflection
.NET 1.1+

Reflecting All Type Members

The eighth part of the Reflection tutorial continues examining how a type's members may be interrogated using reflection. This article looks at how all of the members of a class or structure, regardless of their types, can be examined.

Using Wildcards

When using GetMember you can add a wildcard character to the name parameter to widen the search. Only one wildcard character is permitted. This is the asterisk (*) and must be the final character in the string. It signifies that all members with names that begin with the provided text should be retrieved. The other filtering offered by each overloaded version of GetMember still applies.

The following sample code retrieves all of the public and non-public instance members where the name begins with "TestMethod".

Type type = typeof(MemberTest);
MemberInfo[] members = type.GetMember(
    "TestMethod*", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
Console.WriteLine("{0} member(s)", members.Length);
Console.WriteLine("{0} - {1}", members[0].MemberType, members[0].Name);
Console.WriteLine("{0} - {1}", members[1].MemberType, members[1].Name);

/* OUTPUT

2 member(s)
Method - TestMethod
Method - TestMethodImpl

*/

Obtaining Information for All Members

The System.Type class includes another method that allows you to obtain member information. The GetMembers method has two overloads. The simpler requires no arguments. It retrieves a MemberInfo array containing all of the public members of the target type.

The example below retrieves all of the public members of our sample class. There are nine results, which include the public members we have explicitly defined and the members inherited from the System.Object base class.

Type type = typeof(MemberTest);
MemberInfo[] members = type.GetMembers();
Console.WriteLine("{0} member(s)", members.Length);

/* OUTPUT

9 member(s)

*/

The second overload of GetMembers accepts binding flags to allow you to widen or narrow the query. In the sample code below, all public and non-public instance members are obtained.

Type type = typeof(MemberTest);
MemberInfo[] members = type.GetMembers(
    BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
Console.WriteLine("{0} member(s)", members.Length);

/* OUTPUT

13 member(s)

*/
6 April 2012