Type.FindMembers() Method in C# with Examples
Last Updated :
02 Feb, 2022
Type.FindMembers(MemberTypes, BindingFlags, MemberFilter, Object) Method is used to return a filtered array of MemberInfo objects of the specified member type.
Syntax:
public virtual System.Reflection.MemberInfo[] FindMembers (System.Reflection.MemberTypes memberType, System.Reflection.BindingFlags bindingAttr, System.Reflection.MemberFilter filter, object filterCriteria);
Parameters:
- memberType: It indicates that what type of member should be searched.
- bindingAttr: It used to specify how the search is conducted or Zero, to return null.
- filter: It does the comparisons, returning true if the member currently being inspected matches the filterCriteria and false otherwise.
- filterCriteria: The search criteria that determines whether a member is returned in the array of MemberInfo objects.
The following BindingFlags filter flags can be used to define which members to include in the search:
- You must specify either BindingFlags.Instance or BindingFlags.Static in order to get a return.
- Specify BindingFlags.Instance to include instance members in the search.
- Specify BindingFlags.Static to include static members in the search.
- Specify BindingFlags.Public to include public members in the search.
- Specify BindingFlags.NonPublic to include non-public members (that is, private, internal, and protected members) in the search.
Return Value: This method returns A filtered array of MemberInfo objects of the specified member type. or An empty array of type MemberInfo,
Exception: This method throws ArgumentNullException if filter is null.
Example:
csharp
using System;
using System.Globalization;
using System.Reflection;
class GFG {
public static void Main()
{
Type objType = typeof ( string );
try {
MemberTypes mt = MemberTypes.All;
BindingFlags ba = BindingFlags.Public
| BindingFlags.Instance;
MemberFilter mf = new MemberFilter(Search);
object filterCriteria = "Equals" ;
MemberInfo[] info = objType.FindMembers(mt, ba, mf, filterCriteria);
for ( int index = 0; index < info.Length; index++)
Console.WriteLine( "Result of FindMembers - {0}" ,
info[index].ToString());
}
catch (ArgumentNullException e)
{
Console.Write( "Exception Thrown: " );
Console.Write( "{0}" , e.GetType(), e.Message);
}
}
public static bool Search(MemberInfo info, Object obj)
{
if (info.Name.ToString() == obj.ToString())
return true ;
else
return false ;
}
}
|
Output:
Result of FindMembers - Boolean Equals(System.Object)
Result of FindMembers - Boolean Equals(System.String)
Result of FindMembers - Boolean Equals(System.String, System.StringComparison)
Reference:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...