Export (0) Print
Expand All
Expand Minimize

BindingFlags Enumeration

Specifies flags that control binding and the way in which the search for members and types is conducted by reflection.

This enumeration has a FlagsAttribute attribute that allows a bitwise combination of its member values.

[Visual Basic]
<Flags>
<Serializable>
Public Enum BindingFlags
[C#]
[Flags]
[Serializable]
public enum BindingFlags
[C++]
[Flags]
[Serializable]
__value public enum BindingFlags
[JScript]
public
   Flags
 Serializable
enum BindingFlags

Remarks

These BindingFlags control binding for a great many classes in the System, System.Reflection, and System.Runtime namespaces that invoke, create, get, set, and find members and types.

BindingFlags are used in the following Type methods and other places such as MethodBase.Invoke:

InvokeMember and GetMethod are especially important.

The binding flags are categorized as follows.

Binding Flag Purpose
DeclaredOnly Access Control
FlattenHierarchy Access Control
IgnoreCase Access Control
IgnoreReturn Access Control
Instance Access Control
NonPublic Access Control
Public Access Control
Static Access Control
ExactBinding Change Type
OptionalParamBinding Change Type
CreateInstance Operation Type
GetField Operation Type
SetField Operation Type
GetProperty Operation Type
SetProperty Operation Type
InvokeMethod Operation Type
PutDispProperty Operation Type
PutRefDispProperty Operation Type
Note   You must specify Instance or Static along with Public or NonPublic or no members will be returned.

The following table lists the coercions performed by the default Binder.ChangeType. This table applies especially to the ExactBinding binding flag.

Source Type Target Type
Any type Its base type.
Any type The interface it implements.
Char UInt16, UInt32, Int32, UInt64, Int64, Single, Double
Byte Char, UInt16, Int16, UInt32, Int32, UInt64, Int64, Single, Double
SByte Int16, Int32, Int64, Single, Double
UInt16 UInt32, Int32, UInt64, Int64, Single, Double
Int16 Int32, Int64, Single, Double
UInt32 UInt64, Int64, Single, Double
Int32 Int64, Single, Double
UInt64 Single, Double
Int64 Single, Double
Single Double
Non-reference By-reference.

Members

Member name Description Value
CreateInstance

Supported by the .NET Compact Framework.

Specifies that Reflection should create an instance of the specified type. Calls the constructor that matches the given arguments. The supplied member name is ignored. If the type of lookup is not specified, (Instance | Public) will apply. It is not possible to call a type initializer. 512
DeclaredOnly

Supported by the .NET Compact Framework.

Specifies that only members declared at the level of the supplied type's hierarchy should be considered. Inherited members are not considered. 2
Default

Supported by the .NET Compact Framework.

Specifies no binding flag. 0
ExactBinding

Supported by the .NET Compact Framework.

Specifies that types of the supplied arguments must exactly match the types of the corresponding formal parameters. Reflection throws an exception if the caller supplies a non-null Binder object, since that implies that the caller is supplying BindToXXX implementations that will pick the appropriate method.

Reflection models the accessibility rules of the common type system. For example, if the caller is in the same assembly, the caller does not need special permissions for internal members. Otherwise, the caller needs ReflectionPermission. This is consistent with lookup of members that are protected, private, and so on.

The general principle is that ChangeType should perform only widening coercions, which never lose data. An example of a widening coercion is coercing a value that is a 32-bit signed integer to a value that is a 64-bit signed integer. This is distinguished from a narrowing coercion, which may lose data. An example of a narrowing coercion is coercing a 64-bit signed integer to a 32-bit signed integer.

The default binder ignores this flag, while custom binders can implement the semantics of this flag.

65536
FlattenHierarchy

Supported by the .NET Compact Framework.

Specifies that static members up the hierarchy should be returned. Static members include fields, methods, events, and properties. Nested types are not returned. 64
GetField

Supported by the .NET Compact Framework.

Specifies that the value of the specified field should be returned. 1024
GetProperty

Supported by the .NET Compact Framework.

Specifies that the value of the specified property should be returned. 4096
IgnoreCase

Supported by the .NET Compact Framework.

Specifies that the case of the member name should not be considered when binding. 1
IgnoreReturn

Supported by the .NET Compact Framework.

Used in COM interop to specify that the return value of the member can be ignored. 16777216
Instance

Supported by the .NET Compact Framework.

Specifies that instance members are to be included in the search. 4
InvokeMethod

Supported by the .NET Compact Framework.

Specifies that a method is to be invoked. This may not be a constructor or a type initializer. 256
NonPublic

Supported by the .NET Compact Framework.

Specifies that non-public members are to be included in the search. 32
OptionalParamBinding

Supported by the .NET Compact Framework.

Returns the set of members whose parameter count matches the number of supplied arguments. This binding flag is used for methods with parameters that have default values and methods with variable arguments (varargs). This flag should only be used with Type.InvokeMember.

Parameters with default values are used only in calls where trailing arguments are omitted. They must be the last arguments.

262144
Public

Supported by the .NET Compact Framework.

Specifies that public members are to be included in the search. 16
PutDispProperty

Supported by the .NET Compact Framework.

Specifies that the PROPPUT member on a COM object should be invoked. PROPPUT specifies a property-setting function that uses a value. Use PutDispProperty if a property has both PROPPUT and PROPPUTREF and you need to distinguish which one is called. 16384
PutRefDispProperty

Supported by the .NET Compact Framework.

Specifies that the PROPPUTREF member on a COM object should be invoked. PROPPUTREF specifies a property-setting function that uses a reference instead of a value. Use PutRefDispProperty if a property has both PROPPUT and PROPPUTREF and you need to distinguish which one is called. 32768
SetField

Supported by the .NET Compact Framework.

Specifies that the value of the specified field should be set. 2048
SetProperty

Supported by the .NET Compact Framework.

Specifies that the value of the specified property should be set. For COM properties, specifying this binding flag is equivalent to specifying PutDispProperty and PutRefDispProperty. 8192
Static

Supported by the .NET Compact Framework.

Specifies that static members are to be included in the search. 8
SuppressChangeType

Supported by the .NET Compact Framework.

Not implemented. 131072

Example

[Visual Basic, C#, C++] The following example demonstrates each binding flag.

[Visual Basic] 
Imports System
Imports System.Reflection
Imports System.IO

Class EntryPoint
    Overloads Shared Sub Main(ByVal args() As String)
        Invoke.Go()
    End Sub 'Main
End Class 'EntryPoint



Class Invoke

    Public Shared Sub Go()
        ' BindingFlags.InvokeMethod
        ' Call a static method.
        Dim t As Type = GetType(TestClass)

        Console.WriteLine()
        Console.WriteLine("Invoking a static method.")
        Console.WriteLine("-------------------------")
        t.InvokeMember("SayHello", BindingFlags.InvokeMethod, Nothing, Nothing, New Object() {})

        ' BindingFlags.InvokeMethod
        ' Call an instance method.
        Dim c As New TestClass()
        Console.WriteLine()
        Console.WriteLine("Invoking an instance method.")
        Console.WriteLine("----------------------------")
        c.GetType().InvokeMember("AddUp", BindingFlags.InvokeMethod, Nothing, c, New Object() {})
        c.GetType().InvokeMember("AddUp", BindingFlags.InvokeMethod, Nothing, c, New Object() {})

        ' BindingFlags.InvokeMethod
        ' Call a method with parameters.
        Dim args() As Object = {100.09, 184.45}
        Dim result As Object
        Console.WriteLine()
        Console.WriteLine("Invoking a method with parameters.")
        Console.WriteLine("---------------------------------")
        result = t.InvokeMember("ComputeSum", BindingFlags.InvokeMethod, Nothing, Nothing, args)
        Console.WriteLine("{0} + {1} = {2}", args(0), args(1), result)

        ' BindingFlags.GetField, SetField
        Console.WriteLine()
        Console.WriteLine("Invoking a field (getting and setting.)")
        Console.WriteLine("--------------------------------------")
        ' Get a field value.
        result = t.InvokeMember("Name", BindingFlags.GetField, Nothing, c, New Object() {})
        Console.WriteLine("Name == {0}", result)
        ' Set a field.
        t.InvokeMember("Name", BindingFlags.SetField, Nothing, c, New Object() {"NewName"})
        result = t.InvokeMember("Name", BindingFlags.GetField, Nothing, c, New Object() {})
        Console.WriteLine("Name == {0}", result)

        Console.WriteLine()
        Console.WriteLine("Invoking an indexed property (getting and setting.)")
        Console.WriteLine("--------------------------------------------------")
        ' BindingFlags.GetProperty 
        ' Get an indexed property value.
        Dim index As Integer = 3
        result = t.InvokeMember("Item", BindingFlags.GetProperty, Nothing, c, New Object() {index})
        Console.WriteLine("Item[{0}] == {1}", index, result)
        ' BindingFlags.SetProperty
        ' Set an indexed property value.
        index = 3
        t.InvokeMember("Item", BindingFlags.SetProperty, Nothing, c, New Object() {index, "NewValue"})
        result = t.InvokeMember("Item", BindingFlags.GetProperty, Nothing, c, New Object() {index})
        Console.WriteLine("Item[{0}] == {1}", index, result)

        Console.WriteLine()
        Console.WriteLine("Getting a field or property.")
        Console.WriteLine("----------------------------")
        ' BindingFlags.GetField
        ' Get a field or property.
        result = t.InvokeMember("Name", BindingFlags.GetField Or BindingFlags.GetProperty, Nothing, c, New Object() {})
        Console.WriteLine("Name == {0}", result)
        ' BindingFlags.GetProperty
        result = t.InvokeMember("Value", BindingFlags.GetField Or BindingFlags.GetProperty, Nothing, c, New Object() {})
        Console.WriteLine("Value == {0}", result)

        Console.WriteLine()
        Console.WriteLine("Invoking a method with named parameters.")
        Console.WriteLine("---------------------------------------")
        ' BindingFlags.InvokeMethod
        ' Call a method using named parameters.
        Dim argValues() As Object = {"Mouse", "Micky"}
        Dim argNames() As [String] = {"lastName", "firstName"}
        t.InvokeMember("PrintName", BindingFlags.InvokeMethod, Nothing, Nothing, argValues, Nothing, Nothing, argNames)

        Console.WriteLine()
        Console.WriteLine("Invoking a default member of a type.")
        Console.WriteLine("------------------------------------")
        ' BindingFlags.Default
        ' Call the default member of a type.
        Dim t3 As Type = GetType(TestClass2)
        t3.InvokeMember("", BindingFlags.InvokeMethod Or BindingFlags.Default, Nothing, New TestClass2(), New Object() {})

        Console.WriteLine()
        Console.WriteLine("Invoking a method by reference.")
        Console.WriteLine("-------------------------------")
        ' BindingFlags.Static, NonPublic, and Public
        ' Invoking a member by reference.
        Dim m As MethodInfo = t.GetMethod("Swap")
        args = New Object(1) {}
        args(0) = 1
        args(1) = 2
        m.Invoke(New TestClass(), args)
        Console.WriteLine("{0}, {1}", args(0), args(1))
        ' The string is case-sensitive.
        Dim type As Type = type.GetType("System.String")

        ' Check to see if the value is valid. If the object is null, the type does not exist.
        If type Is Nothing Then
            Console.WriteLine("Please ensure that you specify only valid types in the type field.")
            Console.WriteLine("The type name is case-sensitive.")
            Return
        End If
        ' Declare and populate the arrays to hold the information.
        ' You must declare either NonPublic or Public with Static or the search will not work.
        Dim fi As FieldInfo() = type.GetFields((BindingFlags.Static Or BindingFlags.NonPublic Or BindingFlags.Public))
        ' BindingFlags.NonPublic 
        Dim miNonPublic As MethodInfo() = type.GetMethods((BindingFlags.Static Or BindingFlags.NonPublic))
        ' BindingFlags.Public
        Dim miPublic As MethodInfo() = type.GetMethods((BindingFlags.Static Or BindingFlags.Public))

        ' Iterate through all the nonpublic methods.
        Dim method As MethodInfo
        For Each method In miNonPublic
            Console.WriteLine(method)
        Next method
        ' Iterate through all the public methods.
        For Each method In miPublic
            Console.WriteLine(method)
        Next method
        ' Iterate through all the fields.
        Dim f As FieldInfo
        For Each f In fi
            Console.WriteLine(f)
        Next f

        ' Call an instance method.
        Dim tc As New TestClass()
        Console.WriteLine()
        Console.WriteLine("Invoking an Instance method.")
        Console.WriteLine("----------------------------")
        tc.GetType().InvokeMember("AddUp", BindingFlags.Public Or BindingFlags.Instance Or BindingFlags.CreateInstance, Nothing, tc, New Object() {})

        ' BindingFlags.CreateInstance
        ' Calling and creating an instance method.
        Console.WriteLine()
        Console.WriteLine("Invoking and creating an instance method.")
        Console.WriteLine("-----------------------------------------")
        tc.GetType().InvokeMember("AddUp", BindingFlags.Public Or BindingFlags.Instance Or BindingFlags.CreateInstance, Nothing, tc, New Object() {})

        ' BindingFlags.DeclaredOnly
        Dim tc2 As New TestClass()
        Console.WriteLine()
        Console.WriteLine("DeclaredOnly members")
        Console.WriteLine("---------------------------------")
        Dim memInfo As System.Reflection.MemberInfo() = tc2.GetType().GetMembers(BindingFlags.DeclaredOnly)
        Dim i As Integer
        For i = 0 To memInfo.Length - 1
            Console.WriteLine(memInfo(i).Name)
        Next i

        ' BindingFlags.SuppressChangeType
        Dim obj As New TestClass()
        Console.WriteLine()
        Console.WriteLine("Invoking static method - PrintName")
        Console.WriteLine("---------------------------------")
        Dim methInfo As System.Reflection.MethodInfo = obj.GetType().GetMethod("PrintName")
        methInfo.Invoke(obj, BindingFlags.SuppressChangeType Or BindingFlags.InvokeMethod, Nothing, New Object() {"Brad", "Smith"}, Nothing)

        ' BindingFlags.IgnoreCase
        Console.WriteLine()
        Console.WriteLine("Using IgnoreCase and invoking the PrintName method.")
        Console.WriteLine("---------------------------------------------------")
        methInfo = obj.GetType().GetMethod("PrintName")
        methInfo.Invoke(obj, BindingFlags.IgnoreCase Or BindingFlags.InvokeMethod, Nothing, New Object() {"brad", "smith"}, Nothing)

        ' BindingFlags.IgnoreReturn
        Console.WriteLine()
        Console.WriteLine("Using IgnoreReturn and invoking the PrintName method.")
        Console.WriteLine("-----------------------------------------------------")
        methInfo = obj.GetType().GetMethod("PrintName")
        methInfo.Invoke(obj, BindingFlags.IgnoreReturn Or BindingFlags.InvokeMethod, Nothing, New Object() {"Brad", "Smith"}, Nothing)

        ' BindingFlags.OptionalParamBinding
        Console.WriteLine()
        Console.WriteLine("Using OptionalParamBinding and invoking the PrintName method.")
        Console.WriteLine("-------------------------------------------------------------")
        methInfo = obj.GetType().GetMethod("PrintName")
        methInfo.Invoke(obj, BindingFlags.OptionalParamBinding Or BindingFlags.InvokeMethod, Nothing, New Object() {"Brad", "Smith"}, Nothing)

        ' BindingFlags.ExactBinding
        Console.WriteLine()
        Console.WriteLine("Using ExactBinding and invoking the PrintName method.")
        Console.WriteLine("-----------------------------------------------------")
        methInfo = obj.GetType().GetMethod("PrintName")
        methInfo.Invoke(obj, BindingFlags.ExactBinding Or BindingFlags.InvokeMethod, Nothing, New Object() {"Brad", "Smith"}, Nothing)

        ' BindingFlags.FlattenHierarchy
        Console.WriteLine()
        Console.WriteLine("Using FlattenHierarchy and invoking the PrintName method.")
        Console.WriteLine("---------------------------------------------------------")
        methInfo = obj.GetType().GetMethod("PrintName")
        methInfo.Invoke(obj, BindingFlags.FlattenHierarchy Or BindingFlags.InvokeMethod, Nothing, New Object() {"Brad", "Smith"}, Nothing)
    End Sub 'Go
End Class 'Invoke

Public Class TestClass
    Public Name As [String]
    Private values() As [Object] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}


    Default Public Property Item(ByVal index As Integer) As [Object]
        Get
            Return values(index)
        End Get
        Set(ByVal Value As [Object])
            values(index) = Value
        End Set
    End Property


    Public ReadOnly Property Value() As [Object]
        Get
            Return "the value"
        End Get
    End Property


    Public Sub New()
        Name = "initialName"
    End Sub 'New

    Private methodCalled As Integer = 0


    Public Shared Sub SayHello()
        Console.WriteLine("Hello")
    End Sub 'SayHello


    Public Sub AddUp()
        methodCalled += 1
        Console.WriteLine("AddUp Called {0} times", methodCalled)
    End Sub 'AddUp


    Public Shared Function ComputeSum(ByVal d1 As Double, ByVal d2 As Double) As Double
        Return d1 + d2
    End Function 'ComputeSum


    Public Shared Sub PrintName(ByVal firstName As [String], ByVal lastName As [String])
        Console.WriteLine("{0},{1}", lastName, firstName)
    End Sub 'PrintName


    Public Sub PrintTime()
        Console.WriteLine(DateTime.Now)
    End Sub 'PrintTime


    Public Sub Swap(ByRef a As Integer, ByRef b As Integer)
        Dim x As Integer = a
        a = b
        b = x
    End Sub 'Swap
End Class 'TestClass

<DefaultMemberAttribute("PrintTime")> _
Public Class TestClass2

    Public Sub PrintTime()
        Console.WriteLine(DateTime.Now)
    End Sub 'PrintTime
End Class 'TestClass2

[C#] 
using System;
using System.Reflection;
using System.IO;

namespace BindingFlagsSnippet
{
    class EntryPoint
    {
        static void Main(string[] args)
        {
            Invoke.Go();
        }
    }

    
    class Invoke
    {
        public static void Go()
        {
            // BindingFlags.InvokeMethod
            // Call a static method.
            Type t = typeof (TestClass);

            Console.WriteLine();
            Console.WriteLine("Invoking a static method.");
            Console.WriteLine("-------------------------");
            t.InvokeMember ("SayHello", BindingFlags.InvokeMethod, null, null, new object [] {});

            // BindingFlags.InvokeMethod
            // Call an instance method.
            TestClass c = new TestClass ();
            Console.WriteLine();
            Console.WriteLine("Invoking an instance method.");
            Console.WriteLine("----------------------------");
            c.GetType().InvokeMember ("AddUp", BindingFlags.InvokeMethod, null, c, new object [] {});
            c.GetType().InvokeMember ("AddUp", BindingFlags.InvokeMethod, null, c, new object [] {});
            
            // BindingFlags.InvokeMethod
            // Call a method with parameters.
            object [] args = new object [] {100.09, 184.45};
            object result;
            Console.WriteLine();
            Console.WriteLine("Invoking a method with parameters.");
            Console.WriteLine("---------------------------------");
            result = t.InvokeMember ("ComputeSum", BindingFlags.InvokeMethod, null, null, args);
            Console.WriteLine ("{0} + {1} = {2}", args[0], args[1], result);

            // BindingFlags.GetField, SetField
            Console.WriteLine();
            Console.WriteLine("Invoking a field (getting and setting.)");
            Console.WriteLine("--------------------------------------");
            // Get a field value.
            result = t.InvokeMember ("Name", BindingFlags.GetField, null, c, new object [] {});
            Console.WriteLine ("Name == {0}", result);
            // Set a field.
            t.InvokeMember ("Name", BindingFlags.SetField, null, c, new object [] {"NewName"});
            result = t.InvokeMember ("Name", BindingFlags.GetField, null, c, new object [] {});
            Console.WriteLine ("Name == {0}", result);
            
            Console.WriteLine();
            Console.WriteLine("Invoking an indexed property (getting and setting.)");
            Console.WriteLine("--------------------------------------------------");
            // BindingFlags.GetProperty 
            // Get an indexed property value.
            int  index = 3;
            result = t.InvokeMember ("Item", BindingFlags.GetProperty, null, c, new object [] {index});
            Console.WriteLine ("Item[{0}] == {1}", index, result);
            // BindingFlags.SetProperty
            // Set an indexed property value.
            index = 3;
            t.InvokeMember ("Item", BindingFlags.SetProperty, null, c, new object [] {index, "NewValue"});
            result = t.InvokeMember ("Item", BindingFlags.GetProperty , null, c, new object [] {index});
            Console.WriteLine ("Item[{0}] == {1}", index, result);
            
            Console.WriteLine();
            Console.WriteLine("Getting a field or property.");
            Console.WriteLine("----------------------------");
            // BindingFlags.GetField
            // Get a field or property.
            result = t.InvokeMember ("Name", BindingFlags.GetField | BindingFlags.GetProperty, null, c, new object [] {});
            Console.WriteLine ("Name == {0}", result);
            // BindingFlags.GetProperty
            result = t.InvokeMember ("Value", BindingFlags.GetField | BindingFlags.GetProperty, null, c, new object [] {});
            Console.WriteLine ("Value == {0}", result);

            Console.WriteLine();
            Console.WriteLine("Invoking a method with named parameters.");
            Console.WriteLine("---------------------------------------");
            // BindingFlags.InvokeMethod
            // Call a method using named parameters.
            object[] argValues = new object [] {"Mouse", "Micky"};
            String [] argNames = new String [] {"lastName", "firstName"};
            t.InvokeMember ("PrintName", BindingFlags.InvokeMethod, null, null, argValues, null, null, argNames);

            Console.WriteLine();
            Console.WriteLine("Invoking a default member of a type.");
            Console.WriteLine("------------------------------------");
            // BindingFlags.Default
            // Call the default member of a type.
            Type t3 = typeof (TestClass2);
            t3.InvokeMember ("", BindingFlags.InvokeMethod | BindingFlags.Default, null, new TestClass2(), new object [] {});
 
            // BindingFlags.Static, NonPublic, and Public
            // Invoking a member by reference.
            Console.WriteLine();
            Console.WriteLine("Invoking a method by reference.");
            Console.WriteLine("-------------------------------");
            MethodInfo m = t.GetMethod("Swap");
            args = new object[2];
            args[0] = 1;
            args[1] = 2;
            m.Invoke(new TestClass(),args);
            Console.WriteLine ("{0}, {1}", args[0], args[1]);
            // The string is case-sensitive.
            Type type = Type.GetType("System.String");

            // Check to see if the value is valid. If the object is null, the type does not exist.
            if (type == null) 
            {
                Console.WriteLine("Please ensure that you specify only valid types in the type field.");
                Console.WriteLine("The type name is case-sensitive.");
                return;
            }
            // Declare and populate the arrays to hold the information.
            // You must declare either NonPublic or Public with Static or the search will not work.
            FieldInfo [] fi = type.GetFields (BindingFlags.Static |
                BindingFlags.NonPublic | BindingFlags.Public);  
            // BindingFlags.NonPublic 
            MethodInfo [] miNonPublic = type.GetMethods (BindingFlags.Static |
                BindingFlags.NonPublic);
            // BindingFlags.Public
            MethodInfo [] miPublic = type.GetMethods (BindingFlags.Static |
                BindingFlags.Public);

            // Iterate through all the nonpublic methods.
            foreach (MethodInfo method in miNonPublic) 
            {
                Console.WriteLine(method);
            }
            // Iterate through all the public methods.
            foreach (MethodInfo method in miPublic) 
            {
                Console.WriteLine(method);
            }
            // Iterate through all the fields.
            foreach (FieldInfo f in fi) 
            {
                Console.WriteLine(f);
            }

            // BindingFlags.Instance
            // Call an instance method.
            TestClass tc = new TestClass ();
            Console.WriteLine();
            Console.WriteLine("Invoking an Instance method.");
            Console.WriteLine("----------------------------");
            tc.GetType().InvokeMember ("AddUp", BindingFlags.Public | 
                BindingFlags.Instance | BindingFlags.CreateInstance, 
                null, tc, new object [] {});

            // BindingFlags.CreateInstance
            // Calling and creating an instance method.
            Console.WriteLine();
            Console.WriteLine("Invoking and creating an instance method.");
            Console.WriteLine("-----------------------------------------");
            tc.GetType().InvokeMember ("AddUp", BindingFlags.Public | 
                BindingFlags.Instance | BindingFlags.CreateInstance, 
                null, tc, new object [] {});

            // BindingFlags.DeclaredOnly
            TestClass tc2 = new TestClass();
            Console.WriteLine();
            Console.WriteLine("DeclaredOnly members");
            Console.WriteLine("---------------------------------");
            System.Reflection.MemberInfo[] memInfo = 
                tc2.GetType().GetMembers(BindingFlags.DeclaredOnly);
            for(int i=0;i<memInfo.Length;i++) 
            {
                Console.WriteLine(memInfo[i].Name);
            }

            // BindingFlags.SuppressChangeType
            TestClass obj = new TestClass();
            Console.WriteLine();
            Console.WriteLine("Invoking static method - PrintName");
            Console.WriteLine("---------------------------------");
            System.Reflection.MethodInfo methInfo = 
                obj.GetType().GetMethod("PrintName");
            methInfo.Invoke(obj,BindingFlags.SuppressChangeType | 
                BindingFlags.InvokeMethod, null,new object[] 
                {"Brad","Smith"},null);

            // BindingFlags.IgnoreCase
            Console.WriteLine();
            Console.WriteLine("Using IgnoreCase and invoking the PrintName method.");
            Console.WriteLine("---------------------------------------------------");
            methInfo = obj.GetType().GetMethod("PrintName");
            methInfo.Invoke(obj,BindingFlags.IgnoreCase | 
                BindingFlags.InvokeMethod, null,new object[] 
                {"brad","smith"},null);

            // BindingFlags.IgnoreReturn
            Console.WriteLine();
            Console.WriteLine("Using IgnoreReturn and invoking the PrintName method.");
            Console.WriteLine("-----------------------------------------------------");
            methInfo = obj.GetType().GetMethod("PrintName");
            methInfo.Invoke(obj,BindingFlags.IgnoreReturn | 
                BindingFlags.InvokeMethod, null,new object[] 
                {"Brad","Smith"},null);

            // BindingFlags.OptionalParamBinding
            Console.WriteLine();
            Console.WriteLine("Using OptionalParamBinding and invoking the PrintName method.");
            Console.WriteLine("-------------------------------------------------------------");
            methInfo = obj.GetType().GetMethod("PrintName");
            methInfo.Invoke(obj,BindingFlags.OptionalParamBinding | 
                BindingFlags.InvokeMethod, null,new object[] 
                {"Brad","Smith"},null);

            // BindingFlags.ExactBinding
            Console.WriteLine();
            Console.WriteLine("Using ExactBinding and invoking the PrintName method.");
            Console.WriteLine("-----------------------------------------------------");
            methInfo = obj.GetType().GetMethod("PrintName");
            methInfo.Invoke(obj,BindingFlags.ExactBinding | 
                BindingFlags.InvokeMethod, null,new object[] 
                {"Brad","Smith"},null);
 
            // BindingFlags.FlattenHierarchy
            Console.WriteLine();
            Console.WriteLine("Using FlattenHierarchy and invoking the PrintName method.");
            Console.WriteLine("---------------------------------------------------------");
            methInfo = obj.GetType().GetMethod("PrintName");
            methInfo.Invoke(obj,BindingFlags.FlattenHierarchy | 
                BindingFlags.InvokeMethod, null,new object[] 
                {"Brad","Smith"},null);
        }
    }

    public class TestClass
    {
        public String Name;
        private Object [] values = new Object [] {0, 1,2,3,4,5,6,7,8,9};

        public Object this [int index]
        {
            get 
            {
                return values[index];
            }
            set 
            {
                values[index] = value;
            }
        }

        public Object Value 
        {
            get
            {
                return "the value";
            }
        }

        public TestClass ()
        {
            Name = "initialName";
        }

        int methodCalled = 0;

        public static void SayHello ()
        {
            Console.WriteLine ("Hello");
        }

        public void AddUp ()
        {
            methodCalled++;
            Console.WriteLine ("AddUp Called {0} times", methodCalled);
        }

        public static double ComputeSum (double d1, double d2)
        {
            return d1 + d2;
        }

        public static void PrintName (String firstName, String lastName)
        {
            Console.WriteLine ("{0},{1}", lastName,firstName);
        }

        public void PrintTime ()
        {
            Console.WriteLine (DateTime.Now);
        }

        public void Swap(ref int a, ref int b)
        {
            int x = a;
            a = b;
            b = x;
        }
    }

    [DefaultMemberAttribute ("PrintTime")]
    public class TestClass2
    {
        public void PrintTime ()
        {
            Console.WriteLine (DateTime.Now);
        }
    }
}

[C++] 
#using <mscorlib.dll>

using namespace System;
using namespace System::Collections;
using namespace System::Reflection;
using namespace System::IO;

//namespace BindingFlagsSnippet {

   public __gc class TestClass 
   {
   public:
      String* Name;
   private:
      Object* values[];

   public:
      __property Object* get_Item(int index)
      {
         return values->Item[index];
      }
      __property void set_Item(int index, Object* value)
      {
         values->Item[index] = value;
      }

      __property Object* get_Value() {
         return S"the value";
      }

      int methodCalled;

      TestClass ()
      {
         Name = S"initialName";
         Object* o[] = {__box(0), __box(1), __box(2), __box(3), __box(4),
            __box(5), __box(6), __box(7), __box(8), __box(9)};
         values = o;
         methodCalled = 0;
      }

      static void SayHello () {
         Console::WriteLine (S"Hello");
      }

      void AddUp () {
         methodCalled++;
         Console::WriteLine (S"AddUp Called {0} times", __box(methodCalled));
      }

      static double ComputeSum (double d1, double d2) {
         return d1 + d2;
      }

      static void PrintName (String* firstName, String* lastName) {
         Console::WriteLine (S"{0},{1}", lastName, firstName);
      }

      void PrintTime () {
         Console::WriteLine (__box(DateTime::Now));
      }

      void Swap(int __gc* a, int __gc* b) {
         int x = *a;
         *a = *b;
         *b = x;
      }
   };

   [DefaultMemberAttribute (S"PrintTime")]
   public __gc class TestClass2 
   {
   public:
      void PrintTime () {
         Console::WriteLine (__box(DateTime::Now));
      }
   };

   class Invoke
   {
   public:
      static void Go()
      {
         // BindingFlags::InvokeMethod
         // Call a static method.
         Type* t = __typeof (TestClass);

         Console::WriteLine();
         Console::WriteLine(S"Invoking a static method.");
         Console::WriteLine(S"-------------------------");
         Object* obj1[];
         t->InvokeMember (S"SayHello", BindingFlags::InvokeMethod, 0, 0, obj1);

         // BindingFlags::InvokeMethod
         // Call an instance method.
         TestClass* c = new TestClass ();
         Console::WriteLine();
         Console::WriteLine(S"Invoking an instance method.");
         Console::WriteLine(S"----------------------------");
         c->GetType()->InvokeMember (S"AddUp", BindingFlags::InvokeMethod, 0, c, obj1);
         c->GetType()->InvokeMember (S"AddUp", BindingFlags::InvokeMethod, 0, c, obj1);

         // BindingFlags::InvokeMethod
         // Call a method with parameters.
         Object* args[] = {__box(100.09), __box(184.45)};
         Object* result;
         Console::WriteLine();
         Console::WriteLine(S"Invoking a method with parameters.");
         Console::WriteLine(S"---------------------------------");
         result = t->InvokeMember (S"ComputeSum", BindingFlags::InvokeMethod, 0, 0, args);
         Console::WriteLine (S" {0} + {1} = {2}", args->Item[0], args->Item[1], result);

         // BindingFlags::GetField, SetField
         Console::WriteLine();
         Console::WriteLine(S"Invoking a field (getting and setting.)");
         Console::WriteLine(S"--------------------------------------");
         // Get a field value.
         result = t->InvokeMember (S"Name", BindingFlags::GetField, 0, c, obj1);
         Console::WriteLine (S"Name == {0}", result);
         // Set a field.
         Object* obj2[] = {S"NewName"};
         t->InvokeMember (S"Name", BindingFlags::SetField, 0, c, obj2);
         result = t->InvokeMember (S"Name", BindingFlags::GetField, 0, c, obj1);
         Console::WriteLine (S"Name == {0}", result);

         Console::WriteLine();
         Console::WriteLine(S"Invoking an indexed property (getting and setting.)");
         Console::WriteLine(S"--------------------------------------------------");
         // BindingFlags::GetProperty 
         // Get an indexed property value.
         int  index = 3;
         Object* obj3[] = {__box(index)};
         result = t->InvokeMember (S"Item", BindingFlags::GetProperty, 0, c, obj3);
         Console::WriteLine (S"Item->Item[ {0}] == {1}", __box(index), result);
         // BindingFlags::SetProperty
         // Set an indexed property value.
         index = 3;
         Object* obj4[] = {__box(index), S"NewValue"};
         t->InvokeMember (S"Item", BindingFlags::SetProperty, 0, c, obj4);
         result = t->InvokeMember (S"Item", BindingFlags::GetProperty , 0, c, obj3);
         Console::WriteLine (S"Item->Item[ {0}] == {1}", __box(index), result);

         Console::WriteLine();
         Console::WriteLine(S"Getting a field or property.");
         Console::WriteLine(S"----------------------------");
         // BindingFlags::GetField
         // Get a field or property.
         result = t->InvokeMember (S"Name",
            static_cast<BindingFlags>(BindingFlags::GetField | BindingFlags::GetProperty),
            0, c, obj1);
         Console::WriteLine (S"Name == {0}", result);
         // BindingFlags::GetProperty
         result = t->InvokeMember (S"Value",
            static_cast<BindingFlags>(BindingFlags::GetField | BindingFlags::GetProperty),
            0, c, obj1);
         Console::WriteLine (S"Value == {0}", result);

         Console::WriteLine();
         Console::WriteLine(S"Invoking a method with named parameters.");
         Console::WriteLine(S"---------------------------------------");
         // BindingFlags::InvokeMethod
         // Call a method using named parameters.
         Object* argValues[] = {S"Mouse", S"Micky"};
         String* argNames[] = {S"lastName", S"firstName"};
         t->InvokeMember (S"PrintName", BindingFlags::InvokeMethod, 0, 0, argValues, 0, 0, argNames);

         Console::WriteLine();
         Console::WriteLine(S"Invoking a default member of a type.");
         Console::WriteLine(S"------------------------------------");
         // BindingFlags::Default
         // Call the default member of a type.
         Type* t3 = __typeof (TestClass2);
         t3->InvokeMember (S"", static_cast<BindingFlags>(BindingFlags::InvokeMethod | BindingFlags::Default), 0, new TestClass2(), obj1);

         // BindingFlags::Static, NonPublic, and Public
         // Invoking a member by reference.
         Console::WriteLine();
         Console::WriteLine(S"Invoking a method by reference.");
         Console::WriteLine(S"-------------------------------");
         MethodInfo* m = t->GetMethod(S"Swap");
         args = new Object*[2];
         args[0] = __box(1);
         args[1] = __box(2);
         m->Invoke(new TestClass(), args);
         Console::WriteLine (S"{0}, {1}", args->Item[0], args->Item[1]);
         // The String* is case-sensitive.
         Type* type = Type::GetType(S"System.String");

         // Check to see if the value is valid. If the Object* is 0, the type does not exist.
         if (type == 0) {
            Console::WriteLine(S"Please ensure that you specify only valid types in the type field.");
            Console::WriteLine(S"The type name is case-sensitive.");
            return;
         }
         // Declare and populate the arrays to hold the information.
         // You must declare either NonPublic or Public with Static or the search will not work.
         FieldInfo* fi[] = type->GetFields (static_cast<BindingFlags>(BindingFlags::Static |
            BindingFlags::NonPublic | BindingFlags::Public));  
         // BindingFlags::NonPublic 
         MethodInfo* miNonPublic[] = type->GetMethods (static_cast<BindingFlags>(BindingFlags::Static |
            BindingFlags::NonPublic));
         // BindingFlags::Public
         MethodInfo* miPublic[] = type->GetMethods (static_cast<BindingFlags>(BindingFlags::Static |
            BindingFlags::Public));

         // Iterate through all the nonpublic methods.
         IEnumerator* myEnum1 = miNonPublic->GetEnumerator();
         while (myEnum1->MoveNext()) {
            MethodInfo* method = __try_cast<MethodInfo*>(myEnum1->Current);

            Console::WriteLine(method);
         }
         // Iterate through all the public methods.
         IEnumerator* myEnum2 = miPublic->GetEnumerator();
         while (myEnum2->MoveNext()) {
            MethodInfo* method = __try_cast<MethodInfo*>(myEnum2->Current);

            Console::WriteLine(method);
         }
         // Iterate through all the fields.
         IEnumerator* myEnum3 = fi->GetEnumerator();
         while (myEnum3->MoveNext()) {
            FieldInfo* f = __try_cast<FieldInfo*>(myEnum3->Current);

            Console::WriteLine(f);
         }

         // BindingFlags::Instance
         // Call an instance method.
         TestClass* tc = new TestClass ();
         Console::WriteLine();
         Console::WriteLine(S"Invoking an Instance method.");
         Console::WriteLine(S"----------------------------");
         tc->GetType()->InvokeMember (S"AddUp", static_cast<BindingFlags>(BindingFlags::Public | 
            BindingFlags::Instance | BindingFlags::CreateInstance), 
            0, tc, obj1);

         // BindingFlags::CreateInstance
         // Calling and creating an instance method.
         Console::WriteLine();
         Console::WriteLine(S"Invoking and creating an instance method.");
         Console::WriteLine(S"-----------------------------------------");
         tc->GetType()->InvokeMember (S"AddUp", static_cast<BindingFlags>(BindingFlags::Public | 
            BindingFlags::Instance | BindingFlags::CreateInstance), 
            0, tc, obj1);

         // BindingFlags::DeclaredOnly
         TestClass* tc2 = new TestClass();
         Console::WriteLine();
         Console::WriteLine(S"DeclaredOnly members");
         Console::WriteLine(S"---------------------------------");
         System::Reflection::MemberInfo* memInfo[] = 
            tc2->GetType()->GetMembers(BindingFlags::DeclaredOnly);
         for (int i=0;i<memInfo->Length;i++) {
            Console::WriteLine(memInfo[i]->Name);
         }

         // BindingFlags::SuppressChangeType
         TestClass* obj = new TestClass();
         Console::WriteLine();
         Console::WriteLine(S"Invoking static method - PrintName");
         Console::WriteLine(S"---------------------------------");
         System::Reflection::MethodInfo* methInfo = 
            obj->GetType()->GetMethod(S"PrintName");
         Object* args1[] = {S"Brad", S"Smith"};
         methInfo->Invoke(obj, static_cast<BindingFlags>(BindingFlags::SuppressChangeType | 
            BindingFlags::InvokeMethod), 0, args1, 0);

         // BindingFlags::IgnoreCase
         Console::WriteLine();
         Console::WriteLine(S"Using IgnoreCase and invoking the PrintName method.");
         Console::WriteLine(S"---------------------------------------------------");
         methInfo = obj->GetType()->GetMethod(S"PrintName");
         Object* args2[] = {S"brad", S"smith"};
         methInfo->Invoke(obj, static_cast<BindingFlags>(BindingFlags::IgnoreCase | 
            BindingFlags::InvokeMethod), 0, args2, 0);

         // BindingFlags::IgnoreReturn
         Console::WriteLine();
         Console::WriteLine(S"Using IgnoreReturn and invoking the PrintName method.");
         Console::WriteLine(S"-----------------------------------------------------");
         methInfo = obj->GetType()->GetMethod(S"PrintName");
         Object* args3[] = {S"Brad", S"Smith"};
         methInfo->Invoke(obj, static_cast<BindingFlags>(BindingFlags::IgnoreReturn | 
            BindingFlags::InvokeMethod), 0, args3, 0);

         // BindingFlags::OptionalParamBinding
         Console::WriteLine();
         Console::WriteLine(S"Using OptionalParamBinding and invoking the PrintName method.");
         Console::WriteLine(S"-------------------------------------------------------------");
         methInfo = obj->GetType()->GetMethod(S"PrintName");
         Object* args4[] = {S"Brad", S"Smith"};
         methInfo->Invoke(obj, static_cast<BindingFlags>(BindingFlags::OptionalParamBinding | 
            BindingFlags::InvokeMethod), 0, args4, 0);

         // BindingFlags::ExactBinding
         Console::WriteLine();
         Console::WriteLine(S"Using ExactBinding and invoking the PrintName method.");
         Console::WriteLine(S"-----------------------------------------------------");
         methInfo = obj->GetType()->GetMethod(S"PrintName");
         Object* args5[] = {S"Brad", S"Smith"};
         methInfo->Invoke(obj, static_cast<BindingFlags>(BindingFlags::ExactBinding | 
            BindingFlags::InvokeMethod), 0, args5, 0);

         // BindingFlags::FlattenHierarchy
         Console::WriteLine();
         Console::WriteLine(S"Using FlattenHierarchy and invoking the PrintName method.");
         Console::WriteLine(S"---------------------------------------------------------");
         methInfo = obj->GetType()->GetMethod(S"PrintName");
         Object* args6[] = {S"Brad", S"Smith"};
         methInfo->Invoke(obj, static_cast<BindingFlags>(BindingFlags::FlattenHierarchy | 
            BindingFlags::InvokeMethod), 0, args6, 0);
      }
   };

   int main()
   {
      String* args[] = Environment::GetCommandLineArgs();
      Invoke::Go();
   }
//}

[JScript] No example is available for JScript. To view a Visual Basic, C#, or C++ example, click the Language Filter button Language Filter in the upper-left corner of the page.

Requirements

Namespace: System.Reflection

Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family, .NET Compact Framework

Assembly: Mscorlib (in Mscorlib.dll)

See Also

System.Reflection Namespace

Show:
© 2014 Microsoft