public sealed class EnumBuilder : Type
|
Assembly | Read-only Overridden: Retrieves the dynamic assembly that contains this enum definition. |
AssemblyQualifiedName | Read-only Overridden: Returns the full path of this enum qualified by the display name of the parent assembly. |
Attributes (inherited from System.Type) |
Read-only See base class member description: System.Type.Attributes Gets the attributes associated with the Type. |
BaseType | Read-only Overridden: Returns the parent Type of this type which is always Enum. |
DeclaringType | Read-only Overridden: Returns the type that declared this EnumBuilder. |
FullName | Read-only Overridden: Returns the full path of this enum. |
GUID | Read-only Overridden: Returns the GUID of this enum. |
HasElementType (inherited from System.Type) |
Read-only See base class member description: System.Type.HasElementType Gets a value indicating whether the current Type encompasses or refers to another type; that is, whether the current Type is an array, a pointer, or is passed by reference. |
IsAbstract (inherited from System.Type) |
Read-only See base class member description: System.Type.IsAbstract Gets a value indicating whether the Type is abstract and must be overridden. |
IsAnsiClass (inherited from System.Type) |
Read-only See base class member description: System.Type.IsAnsiClass Gets a value indicating whether the string format attribute AnsiClass is selected for the Type. |
IsArray (inherited from System.Type) |
Read-only See base class member description: System.Type.IsArray Gets a value indicating whether the Type is an array. |
IsAutoClass (inherited from System.Type) |
Read-only See base class member description: System.Type.IsAutoClass Gets a value indicating whether the string format attribute AutoClass is selected for the Type. |
IsAutoLayout (inherited from System.Type) |
Read-only See base class member description: System.Type.IsAutoLayout Gets a value indicating whether the class layout attribute AutoLayout is selected for the Type. |
IsByRef (inherited from System.Type) |
Read-only See base class member description: System.Type.IsByRef Gets a value indicating whether the Type is passed by reference. |
IsClass (inherited from System.Type) |
Read-only See base class member description: System.Type.IsClass Gets a value indicating whether the Type is a class; that is, not a value type or interface. |
IsCOMObject (inherited from System.Type) |
Read-only See base class member description: System.Type.IsCOMObject Gets a value indicating whether the Type is a COM object. |
IsContextful (inherited from System.Type) |
Read-only See base class member description: System.Type.IsContextful Gets a value indicating whether the Type can be hosted in a context. |
IsEnum (inherited from System.Type) |
Read-only See base class member description: System.Type.IsEnum Gets a value indicating whether the current Type represents an enumeration. |
IsExplicitLayout (inherited from System.Type) |
Read-only See base class member description: System.Type.IsExplicitLayout Gets a value indicating whether the class layout attribute ExplicitLayout is selected for the Type. |
IsImport (inherited from System.Type) |
Read-only See base class member description: System.Type.IsImport Gets a value indicating whether the Type was imported from another class. |
IsInterface (inherited from System.Type) |
Read-only See base class member description: System.Type.IsInterface Gets a value indicating whether the Type is an interface; that is, not a class or a value type. |
IsLayoutSequential (inherited from System.Type) |
Read-only See base class member description: System.Type.IsLayoutSequential Gets a value indicating whether the class layout attribute SequentialLayout is selected for the Type. |
IsMarshalByRef (inherited from System.Type) |
Read-only See base class member description: System.Type.IsMarshalByRef Gets a value indicating whether the Type is marshaled by reference. |
IsNestedAssembly (inherited from System.Type) |
Read-only See base class member description: System.Type.IsNestedAssembly Gets a value indicating whether the Type is nested and visible only within its own assembly. |
IsNestedFamANDAssem (inherited from System.Type) |
Read-only See base class member description: System.Type.IsNestedFamANDAssem Gets a value indicating whether the Type is nested and visible only to classes that belong to both its own family and its own assembly. |
IsNestedFamily (inherited from System.Type) |
Read-only See base class member description: System.Type.IsNestedFamily Gets a value indicating whether the Type is nested and visible only within its own family. |
IsNestedFamORAssem (inherited from System.Type) |
Read-only See base class member description: System.Type.IsNestedFamORAssem Gets a value indicating whether the Type is nested and visible only to classes that belong to either its own family or to its own assembly. |
IsNestedPrivate (inherited from System.Type) |
Read-only See base class member description: System.Type.IsNestedPrivate Gets a value indicating whether the Type is nested and declared private. |
IsNestedPublic (inherited from System.Type) |
Read-only See base class member description: System.Type.IsNestedPublic Gets a value indicating whether a class is nested and declared public. |
IsNotPublic (inherited from System.Type) |
Read-only See base class member description: System.Type.IsNotPublic Gets a value indicating whether the top-level Type is not declared public. |
IsPointer (inherited from System.Type) |
Read-only See base class member description: System.Type.IsPointer Gets a value indicating whether the Type is a pointer. |
IsPrimitive (inherited from System.Type) |
Read-only See base class member description: System.Type.IsPrimitive Gets a value indicating whether the Type is one of the primitive types. |
IsPublic (inherited from System.Type) |
Read-only See base class member description: System.Type.IsPublic Gets a value indicating whether the top-level Type is declared public. |
IsSealed (inherited from System.Type) |
Read-only See base class member description: System.Type.IsSealed Gets a value indicating whether the Type is declared sealed. |
IsSerializable (inherited from System.Type) |
Read-only See base class member description: System.Type.IsSerializable Gets a value indicating whether the Type is serializable. |
IsSpecialName (inherited from System.Type) |
Read-only See base class member description: System.Type.IsSpecialName Gets a value indicating whether the Type has a name that requires special handling. |
IsUnicodeClass (inherited from System.Type) |
Read-only See base class member description: System.Type.IsUnicodeClass Gets a value indicating whether the string format attribute UnicodeClass is selected for the Type. |
IsValueType (inherited from System.Type) |
Read-only See base class member description: System.Type.IsValueType Gets a value indicating whether the Type is a value type. |
MemberType (inherited from System.Type) |
Read-only See base class member description: System.Type.MemberType Gets a bitmask indicating the member type. |
Module | Read-only Overridden: Retrieves the dynamic module that contains this EnumBuilder definition. |
Name | Read-only Overridden: Returns the name of this enum. |
Namespace | Read-only Overridden: |
ReflectedType | Read-only Overridden: Returns the type that was used to obtain this EnumBuilder. |
TypeHandle | Read-only Overridden: Retrieves the internal handle for this enum. |
TypeInitializer (inherited from System.Type) |
Read-only See base class member description: System.Type.TypeInitializer Gets the initializer for the Type. |
TypeToken | Read-only Returns the internal metadata type token of this enum. |
UnderlyingField | Read-only Returns the underlying field for this enum. |
UnderlyingSystemType | Read-only Overridden: Returns the underlying system type for this enum. |
CreateType | Creates a Type object for this enum. |
DefineLiteral | Defines the named static field in an enumeration type with the specified constant value. |
Equals (inherited from System.Type) |
Overloaded:Equals(object o) See base class member description: System.Type.EqualsDetermines if the underlying system type of the current Type is the same as the underlying system type of the specified Object. |
Equals (inherited from System.Type) |
Overloaded:Equals(Type o) See base class member description: System.Type.EqualsDetermines if the underlying system type of the current Type is the same as the underlying system type of the specified Type. |
FindInterfaces (inherited from System.Type) |
See base class member description: System.Type.FindInterfaces Returns an array of Type objects representing a filtered list of interfaces implemented or inherited by the current Type. |
FindMembers (inherited from System.Type) |
See base class member description: System.Type.FindMembers Returns a filtered array of MemberInfo objects of the specified member type. |
GetArrayRank (inherited from System.Type) |
See base class member description: System.Type.GetArrayRank Gets the number of dimensions in an Array. |
GetConstructor (inherited from System.Type) |
Overloaded:GetConstructor(Type[] types) See base class member description: System.Type.GetConstructorSearches for a public instance constructor whose parameters match the types in the specified array. |
GetConstructor (inherited from System.Type) |
Overloaded:GetConstructor(BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers) See base class member description: System.Type.GetConstructorSearches for a constructor whose parameters match the specified argument types and modifiers, using the specified binding constraints. |
GetConstructor (inherited from System.Type) |
Overloaded:GetConstructor(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) See base class member description: System.Type.GetConstructorSearches for a constructor whose parameters match the specified argument types and modifiers, using the specified binding constraints and the specified calling convention. |
GetConstructors (inherited from System.Type) |
Overloaded:GetConstructors() See base class member description: System.Type.GetConstructorsReturns all the public constructors defined for the current Type. |
GetConstructors | Overloaded:GetConstructors(BindingFlags bindingAttr) Overridden: Returns an array of ConstructorInfo objects representing the public and non-public constructors defined for this class, as specified. |
GetCustomAttributes | Overloaded:GetCustomAttributes(bool inherit) Overridden: Returns all the custom attributes defined for this constructor. |
GetCustomAttributes | Overloaded:GetCustomAttributes(Type attributeType, bool inherit) Overridden: Returns the custom attributes identified by the given type. |
GetDefaultMembers (inherited from System.Type) |
See base class member description: System.Type.GetDefaultMembers Searches for the members defined for the current Type whose DefaultMemberAttribute is set. |
GetElementType | Overridden: Calling this method always throws NotSupportedException. |
GetEvent (inherited from System.Type) |
Overloaded:GetEvent(string name) See base class member description: System.Type.GetEventReturns the EventInfo object representing the specified event. |
GetEvent | Overloaded:GetEvent(string name, BindingFlags bindingAttr) Overridden: Returns the event with the specified name. |
GetEvents | Overloaded:GetEvents() Overridden: Returns the events for the public events declared or inherited by this type. |
GetEvents | Overloaded:GetEvents(BindingFlags bindingAttr) Overridden: Returns the public and non-public events that are declared by this type. |
GetField (inherited from System.Type) |
Overloaded:GetField(string name) See base class member description: System.Type.GetFieldSearches for the field with the specified name. |
GetField | Overloaded:GetField(string name, BindingFlags bindingAttr) Overridden: Returns the field specified by the given name. |
GetFields (inherited from System.Type) |
Overloaded:GetFields() See base class member description: System.Type.GetFieldsReturns all the public fields of the current Type. |
GetFields | Overloaded:GetFields(BindingFlags bindingAttr) Overridden: Returns the public and non-public fields that are declared by this type. |
GetHashCode (inherited from System.Type) |
See base class member description: System.Type.GetHashCode Returns the hash code for this instance. |
GetInterface (inherited from System.Type) |
Overloaded:GetInterface(string name) See base class member description: System.Type.GetInterfaceSearches for the interface with the specified name. |
GetInterface | Overloaded:GetInterface(string name, bool ignoreCase) Overridden: Returns the interface implemented (directly or indirectly) by this class with the fully-qualified name matching the given interface name. |
GetInterfaceMap | Overridden: Returns an interface mapping for the interface requested. |
GetInterfaces | Overridden: Returns an array of all the interfaces implemented on this a class and its base classes. |
GetMember (inherited from System.Type) |
Overloaded:GetMember(string name) See base class member description: System.Type.GetMemberSearches for the members with the specified name. |
GetMember (inherited from System.Type) |
Overloaded:GetMember(string name, BindingFlags bindingAttr) See base class member description: System.Type.GetMemberSearches for the specified members, using the specified binding constraints. |
GetMember | Overloaded:GetMember(string name, MemberTypes type, BindingFlags bindingAttr) Overridden: Returns all the public and non-public members declared or inherited by this type, as specified. |
GetMembers (inherited from System.Type) |
Overloaded:GetMembers() See base class member description: System.Type.GetMembersReturns all the public members of the current Type. |
GetMembers | Overloaded:GetMembers(BindingFlags bindingAttr) Overridden: Returns all the public and non-public members declared or inherited by this type, as specified. |
GetMethod (inherited from System.Type) |
Overloaded:GetMethod(string name) See base class member description: System.Type.GetMethodSearches for the public method with the specified name. |
GetMethod (inherited from System.Type) |
Overloaded:GetMethod(string name, BindingFlags bindingAttr) See base class member description: System.Type.GetMethodSearches for the specified method, using the specified binding constraints. |
GetMethod (inherited from System.Type) |
Overloaded:GetMethod(string name, Type[] types) See base class member description: System.Type.GetMethodSearches for the specified public method whose parameters match the specified argument types. |
GetMethod (inherited from System.Type) |
Overloaded:GetMethod(string name, Type[] types, ParameterModifier[] modifiers) See base class member description: System.Type.GetMethodSearches for the specified public method whose parameters match the specified argument types and modifiers. |
GetMethod (inherited from System.Type) |
Overloaded:GetMethod(string name, BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers) See base class member description: System.Type.GetMethodSearches for the specified method whose parameters match the specified argument types and modifiers, using the specified binding constraints. |
GetMethod (inherited from System.Type) |
Overloaded:GetMethod(string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) See base class member description: System.Type.GetMethodSearches for the specified method whose parameters match the specified argument types and modifiers, using the specified binding constraints and the specified calling convention. |
GetMethods (inherited from System.Type) |
Overloaded:GetMethods() See base class member description: System.Type.GetMethodsReturns all the public methods of the current Type. |
GetMethods | Overloaded:GetMethods(BindingFlags bindingAttr) Overridden: Returns all the public and non-public methods declared or inherited by this type, as specified. |
GetNestedType (inherited from System.Type) |
Overloaded:GetNestedType(string name) See base class member description: System.Type.GetNestedTypeSearches for the nested type with the specified name. |
GetNestedType | Overloaded:GetNestedType(string name, BindingFlags bindingAttr) Overridden: Returns the public and non-public nested types that are declared by this type. |
GetNestedTypes (inherited from System.Type) |
Overloaded:GetNestedTypes() See base class member description: System.Type.GetNestedTypesReturns all the types nested within the current Type. |
GetNestedTypes | Overloaded:GetNestedTypes(BindingFlags bindingAttr) Overridden: Returns the public and non-public nested types that are declared or inherited by this type. |
GetProperties (inherited from System.Type) |
Overloaded:GetProperties() See base class member description: System.Type.GetPropertiesReturns all the public properties of the current Type. |
GetProperties | Overloaded:GetProperties(BindingFlags bindingAttr) Overridden: Returns all the public and non-public properties declared or inherited by this type, as specified. |
GetProperty (inherited from System.Type) |
Overloaded:GetProperty(string name) See base class member description: System.Type.GetPropertySearches for the public property with the specified name. |
GetProperty (inherited from System.Type) |
Overloaded:GetProperty(string name, BindingFlags bindingAttr) See base class member description: System.Type.GetPropertySearches for the specified property, using the specified binding constraints. |
GetProperty (inherited from System.Type) |
Overloaded:GetProperty(string name, Type returnType) See base class member description: System.Type.GetPropertySearches for the public property with the specified name and return type. |
GetProperty (inherited from System.Type) |
Overloaded:GetProperty(string name, Type[] types) See base class member description: System.Type.GetPropertySearches for the specified public property whose parameters match the specified argument types. |
GetProperty (inherited from System.Type) |
Overloaded:GetProperty(string name, Type returnType, Type[] types) See base class member description: System.Type.GetPropertySearches for the specified public property whose parameters match the specified argument types. |
GetProperty (inherited from System.Type) |
Overloaded:GetProperty(string name, Type returnType, Type[] types, ParameterModifier[] modifiers) See base class member description: System.Type.GetPropertySearches for the specified public property whose parameters match the specified argument types and modifiers. |
GetProperty (inherited from System.Type) |
Overloaded:GetProperty(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) See base class member description: System.Type.GetPropertySearches for the specified property whose parameters match the specified argument types and modifiers, using the specified binding constraints. |
GetType (inherited from System.Object) |
See base class member description: System.Object.GetType Derived from System.Object, the primary base class for all objects. |
InvokeMember (inherited from System.Type) |
Overloaded:InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args) See base class member description: System.Type.InvokeMemberInvokes the specified member, using the specified binding constraints and matching the specified argument list. |
InvokeMember (inherited from System.Type) |
Overloaded:InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, CultureInfo culture) See base class member description: System.Type.InvokeMemberInvokes the specified member, using the specified binding constraints and matching the specified argument list and culture. |
InvokeMember | Overloaded:InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters) Overridden: Invokes the specified member. The method that is to be invoked must be accessible and provide the most specific match with the specified argument list, under the contraints of the specified binder and invocation attributes. |
IsAssignableFrom (inherited from System.Type) |
See base class member description: System.Type.IsAssignableFrom Determines whether an instance of the current Type can be assigned from an instance of the specified Type. |
IsDefined | Overridden: Checks if the specified custom attribute type is defined. |
IsInstanceOfType (inherited from System.Type) |
See base class member description: System.Type.IsInstanceOfType Determines whether the specified object is an instance of the current Type. |
IsSubclassOf (inherited from System.Type) |
See base class member description: System.Type.IsSubclassOf Determines whether the current Type derives from the specified Type. |
SetCustomAttribute | Overloaded:SetCustomAttribute(CustomAttributeBuilder customBuilder) Sets a custom attribute using a custom attribute builder. |
SetCustomAttribute | Overloaded:SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) Sets a custom attribute using a specified custom attribute blob. |
ToString (inherited from System.Type) |
See base class member description: System.Type.ToString Returns a String representing the name of the current Type. |
Finalize (inherited from System.Object) |
See base class member description: System.Object.Finalize Derived from System.Object, the primary base class for all objects. |
GetAttributeFlagsImpl | Overridden: Gets the implementation attribute flags. |
GetConstructorImpl | Overridden: Searches for a constructor whose parameters match the specified argument types and modifiers, using the specified binding constraints and the specified calling convention. |
GetMethodImpl | Overridden: Searches for the specified method whose parameters match the specified argument types and modifiers, using the specified binding constraints and the specified calling convention. |
GetPropertyImpl | Overridden: Searches for the specified property whose parameters match the specified argument types and modifiers, using the specified binding constraints. |
HasElementTypeImpl | Overridden: Calling this method always throws NotSupportedException. |
IsArrayImpl | Overridden: |
IsByRefImpl | Overridden: Returns false. |
IsCOMObjectImpl | Overridden: |
IsContextfulImpl (inherited from System.Type) |
See base class member description: System.Type.IsContextfulImpl Implements the Type.IsContextful property and determines whether the Type can be hosted in a context. |
IsMarshalByRefImpl (inherited from System.Type) |
See base class member description: System.Type.IsMarshalByRefImpl Implements the Type.IsMarshalByRef property and determines whether the Type is marshalled by reference. |
IsPointerImpl | Overridden: Returns false. |
IsPrimitiveImpl | Overridden: |
IsValueTypeImpl | Overridden: |
MemberwiseClone (inherited from System.Object) |
See base class member description: System.Object.MemberwiseClone Derived from System.Object, the primary base class for all objects. |
Hierarchy:
public override Assembly Assembly {get;}
|
public override string AssemblyQualifiedName {get;}
|
Exception Type | Condition |
---|---|
NotSupportedException | If EnumBuilder.CreateType has not been called previously. |
<FullTypeName>, <AssemblyDisplayName>
See AssemblyName for a description of the format of the display name of an assembly.
public TypeAttributes Attributes {get;}
|
public override Type BaseType {get;}
|
public override Type DeclaringType {get;}
|
public override string FullName {get;}
|
public override Guid GUID {get;}
|
Exception Type | Condition |
---|---|
NotSupportedException | This method is not currently supported in types that are not complete. |
public bool HasElementType {get;}
|
public class MyClass { } public class Type_HasElementType { public static void Main() { try { // An non array or pointer or reference element. MyClass myObject1 = new MyClass(); Object myObject2 = myObject1 ; // An object of array type. MyClass[] myObject3 = new MyClass[5]; Object myObject4 = myObject3 ; Object[] myObjects = new Object[] { myObject1, myObject2, myObject3, myObject4 }; Console.WriteLine("\nCheck whether the object refers to array or pointer or reference type.\n"); for(int i = 0; i < myObjects.Length; i++) { if(myObjects[i].GetType().HasElementType) Console.WriteLine("'myObject{0}' refers to an array or pointer or reference", i); else Console.WriteLine("'myObject{0}' does not refer to an array or pointer or reference", i); } } catch( Exception e ) { Console.WriteLine( "Exception: {0} \n", e.Message ) ; } } }
public bool IsAbstract {get;}
|
public abstract class MyAbstractClass { } public class MyClass { } public class Type_IsAbstract { public static void Main() { try { Console.WriteLine("\nChecking whether the type is abstract\n"); // Check whether the return Type is abstract or not. Console.WriteLine("'MyAbstractClass' is {0}", (typeof(MyAbstractClass).IsAbstract) ? "an abstract class" : "not an abstract class" ); // Check whether the return Type is abstract or not. Console.WriteLine("'MyClass' is {0}", (typeof(MyClass).IsAbstract) ? "an abstract class" : "not an abstract class" ); } catch( Exception e ) { Console.WriteLine( "Exception: {0} \n", e.Message ); } } }
public bool IsAnsiClass {get;}
|
public class MyClass { protected string myField = "A sample protected field" ; } public class MyType_IsAnsiClass { public static void Main() { try { MyClass myObject = new MyClass(); // Get the type of the 'MyClass'. Type myType = typeof(MyClass); // Get the field information and the attributes associated with 'MyClass'. FieldInfo myFieldInfo = myType.GetField("myField", BindingFlags.NonPublic|BindingFlags.Instance); Console.WriteLine( "\nChecking for AnsiClass attribute for a field\n"); // Get and display the name, field, and the AnsiClass attribute. Console.WriteLine("Name of Class: {0} \nValue of Field: {1} \nIsAnsiClass = {2}", myType.FullName, myFieldInfo.GetValue(myObject), myType.IsAnsiClass); } catch(Exception e) { Console.WriteLine("Exception : {0}",e.Message); } } }
public bool IsArray {get;}
|
This property is read-only.
using System; class TestIsArray { public static void Main() { int [] array = {1,2,3,4}; Type at = typeof(Array); Type t = array.GetType(); Console.WriteLine("Type is {0}. IsArray? {1}", at, at.IsArray); Console.WriteLine("Type is {0}. IsArray? {1}", t, t.IsArray); } }
This code produces the following output:
Type is System.Array. IsArray? False Type is System.Int32[]. IsArray? True
public bool IsAutoClass {get;}
|
public bool IsAutoLayout {get;}
|
Use the AutoLayout attribute to let the runtime engine decide the best way to layout the objects of the class. Classes marked with the AutoLayout attribute indicate that the loader will choose the appropriate way to lay out the class; any layout information that may have been specified is ignored.
// The MyDemoAttribute class is selected as AutoLayout. [StructLayoutAttribute(LayoutKind.Auto)] public class MyDemoAttribute { } public class MyTypeClass { public static void Main(string[] args) { MyAutoLayoutMethod("MyDemoAttribute"); } public static void MyAutoLayoutMethod(string typeName) { try { // Create an object of 'Type' class using the 'GetType' method. Type myType=Type.GetType(typeName); // Get and display the 'IsAutoLayout' property of the // 'MyDemoAttribute' instance. Console.WriteLine("\n The 'Autolayout' property for the 'MyDemoAttribute' is: {0}.",myType.IsAutoLayout); } catch(Exception e) { Console.WriteLine("\nThe following exception is raised: {0}." ,e.Message); } } }
public bool IsByRef {get;}
|
public bool IsClass {get;}
|
The TypeAttributes.ClassSemanticsMask distinguishes a type declaration as class, interface, or value type.
This property is read-only.
public class MyDemoClass { } public class MyTypeClass { public static void Main(string[] args) { try { Type myType=Type.GetType("MyDemoClass"); // Get and display the 'IsClass' property of the 'MyDemoClass' instance. Console.WriteLine("\n'MyDemoClass' is of type 'Class': {0}.", myType.IsClass); } catch(Exception e) { Console.WriteLine("\nThe following exception is raised: {0}." ,e.Message); } } }
public bool IsCOMObject {get;}
|
You can also load a COM class and get a Type object for that COM class by using the tool.
public bool IsContextful {get;}
|
public class MyContextBoundClass: ContextBoundObject { public string myString = "This class demonstrates the isContextful and isMarshalByRef properties."; } public class MyTypeDemoClass { public static void Main() { try { // Check if the types can be hosted in a Context. Console.WriteLine ("The Contextful property for the '{0}' type is: {1}", typeof(MyTypeDemoClass).Name, typeof(MyTypeDemoClass).IsContextful); Console.WriteLine ("The Contextful property for the '{0}' type is: {1}", typeof(MyContextBoundClass).Name, typeof(MyContextBoundClass).IsContextful); // Check if the types are marshalled by reference. Console.WriteLine ("The MarshalByRef property of '{0}' is: {1} ", typeof(MyTypeDemoClass).Name, typeof(MyTypeDemoClass).IsMarshalByRef); Console.WriteLine ("The MarshalByRef property of '{0}' is: {1} ", typeof(MyContextBoundClass).Name, typeof(MyContextBoundClass).IsMarshalByRef); // Check if the types are primitive datatypes. Console.WriteLine ("'{0}' is a primitive datatype : {1} ", typeof(int).Name, typeof(int).IsPrimitive); Console.WriteLine ("'{0}' is a primitive datatype : {1} ", typeof(string).Name, typeof(string).IsPrimitive); } catch (Exception e) { Console.WriteLine("The following exception is raised : " + e.Message); } } }
public bool IsEnum {get;}
|
This property is read-only.
using System; public enum Color { Red, Blue, Green } class TestIsEnum { public static void Main() { Type colorType = typeof(Color); Type enumType = typeof(Enum); Console.WriteLine("Color is enum? {0}", colorType.IsEnum); Console.WriteLine("Color is valueType? {0}", colorType.IsValueType); Console.WriteLine("Enum is enum Type? {0}", enumType.IsEnum); Console.WriteLine("Enum is value? {0}", enumType.IsValueType); } }
This code produces the following output:
Color is enum? True Color is valueType? True Enum is enum Type? False Enum is value? False
public bool IsExplicitLayout {get;}
|
Classes marked with the ExplicitLayout attribute cause the loader to ignore field sequence and to use the explicit layout rules provided, in the form of field offsets, overall class size and alignment, or all of these.
Use the ExplicitLayout attribute to specify the offsets at which each field starts, or to specify the overall size and, optionally, the packing size of the objects of the class. The packing size is the empty memory space between fields and must be 1, 2, 4, 8 or 16 bytes.
//The class is selected for the ExplicitLayout. [StructLayoutAttribute(LayoutKind.Explicit)] public class MyDemoAttribute { } public class MyTypeClass { public static void Main(string[] args) { MyIsExplicitLayoutMethod("MyDemoAttribute"); } public static void MyIsExplicitLayoutMethod(string typeName) { try { // Create an object of 'Type' class using the 'GetType' method. Type myType=Type.GetType(typeName); // Get and display the 'IsExplicitLayout' property. Console.WriteLine("\n'MyDemoAttribute' instance's 'IsExplicitLayout' property is: {0}.",myType.IsExplicitLayout); } catch(Exception e) { Console.WriteLine("\nThe following exception is raised: {0}." ,e.Message); } } }
public bool IsImport {get;}
|
public bool IsInterface {get;}
|
This property is read-only.
// Interface declaration. interface myIFace { } class MyIsInterface { public static void Main(string []args) { try { // Get the attribute IsInterface for myIFace. bool myBool1 = typeof(myIFace).IsInterface; //Display the IsInterface attribute for myIFace. Console.WriteLine("The type mentioned is an interface: {0}",myBool1); // Get the attribute IsInterface for MyIsInterface. bool myBool2 = typeof(MyIsInterface).IsInterface; //Display the IsInterface attribute for MyIsInterface. Console.WriteLine("The type mentioned is an interface: {0}",myBool2); } catch(Exception e) { Console.WriteLine("\nThe following exception is raised : {0}",e.Message); } } }
public bool IsLayoutSequential {get;}
|
Classes marked with the SequentialLayout attribute guides the loader to preserve field order as emitted, but otherwise the specific offsets are calculated based on the common language runtime type of the field; these may be shifted by explicit offset, padding, or alignment information.
Use the SequentialLayout attribute to layout the objects of the class sequentially and to specify the packing size between adjacent fields. The packing size is the empty memory space between fields and must be 1, 2, 4, 8 or 16 bytes. A field will be aligned to its natural size or to the packing size, whichever results in a smaller offset.
// MyTypeSequential1 class declaration. class MyTypeSequential1 { } [StructLayoutAttribute(LayoutKind.Sequential)] class MyTypeSequential2 { public static void Main(string []args) { try { // Create an instance of 'myTypeSeq1' class. MyTypeSequential1 myObj1 = new MyTypeSequential1(); Type myTypeObj1 = myObj1.GetType(); // Check and displays the attribute 'SequentialLayout'. Console.WriteLine("\nThe object myObj1 has 'IsLayoutSequential': {0}", myObj1.GetType().IsLayoutSequential); // Create an instance of 'myTypeSeq2' class. MyTypeSequential2 myObj2 = new MyTypeSequential2(); Type myTypeObj2 = myObj2.GetType(); // Check and displays the attribute 'SequentialLayout'. Console.WriteLine("\nThe object myObj2 has 'IsLayoutSequential': {0}", myObj2.GetType().IsLayoutSequential); } catch(Exception e) { Console.WriteLine("\nThe following exception is raised: {0}",e.Message); } } }
public bool IsMarshalByRef {get;}
|
public class MyContextBoundClass: ContextBoundObject { public string myString = "This class demonstrates the isContextful and isMarshalByRef properties."; } public class MyTypeDemoClass { public static void Main() { try { // Check if the types can be hosted in a Context. Console.WriteLine ("The Contextful property for the '{0}' type is: {1}", typeof(MyTypeDemoClass).Name, typeof(MyTypeDemoClass).IsContextful); Console.WriteLine ("The Contextful property for the '{0}' type is: {1}", typeof(MyContextBoundClass).Name, typeof(MyContextBoundClass).IsContextful); // Check if the types are marshalled by reference. Console.WriteLine ("The MarshalByRef property of '{0}' is: {1} ", typeof(MyTypeDemoClass).Name, typeof(MyTypeDemoClass).IsMarshalByRef); Console.WriteLine ("The MarshalByRef property of '{0}' is: {1} ", typeof(MyContextBoundClass).Name, typeof(MyContextBoundClass).IsMarshalByRef); // Check if the types are primitive datatypes. Console.WriteLine ("'{0}' is a primitive datatype : {1} ", typeof(int).Name, typeof(int).IsPrimitive); Console.WriteLine ("'{0}' is a primitive datatype : {1} ", typeof(string).Name, typeof(string).IsPrimitive); } catch (Exception e) { Console.WriteLine("The following exception is raised : " + e.Message); } } }
public bool IsNestedAssembly {get;}
|
// Enclose a class. class MyClassA { // Internal nested class. internal class MyClassB { } } class MyTestClass { public static void Main(string[] args) { // Get the Type of the nested class. Type myTypeB = typeof(MyClassA.MyClassB); // Get the 'IsNestedAssembly' property of the nested class // 'Type'. Console.WriteLine("\nThe nested class has the property 'IsNestedAssembly' value: "+ myTypeB.IsNestedAssembly.ToString()); } }
public bool IsNestedFamANDAssem {get;}
|
A Type object's family is defined as all objects of the exact same Type and of its subtypes.
public bool IsNestedFamily {get;}
|
A Type object's family is defined as all objects of the exact same Type and of its subtypes.
// Enclose a class. class MyClassA { // Protected nested class. protected class MyClassB { } } class MyTestClass : MyClassA { public static void Main(string[] args) { // Get the Type of the nested class. Type myTypeB = typeof(MyClassA.MyClassB); // Get the 'IsNestedFamily' property the of the nested class // 'Type'. Console.WriteLine("\nThe nested class has the property 'IsNestedFamily' value: "+ myTypeB.IsNestedFamily.ToString()); } }
public bool IsNestedFamORAssem {get;}
|
A Type object's family is defined as all objects of the exact same Type and of its subtypes.
// Enclose a class. class MyClassA { // Protected internal nested class. protected internal class MyClassB { } } class MyTestClass { public static void Main(string[] args) { // Get the Type of the nested class. Type myTypeB = typeof(MyClassA.MyClassB); // Get the 'IsNestedFamORAssem' property of the nested class // 'Type'. Console.WriteLine("\nThe nested class has the property 'IsNestedFamORAssem' value: "+ myTypeB.IsNestedFamORAssem.ToString()); } }
public bool IsNestedPrivate {get;}
|
// Outer class. public class MyClassA { // Private nested class. private class MyClassB { } public static void Main(string[] args) { // Get the Type of the nested class. Type myTypeB = typeof(MyClassA.MyClassB); // Get the 'IsNestedPrivate' property of the nested class 'Type'. Console.WriteLine("\nThe nested class has the property 'IsNestedPrivate'value: "+ myTypeB.IsNestedPrivate.ToString()); } }
public bool IsNestedPublic {get;}
|
using System; // Enclose a class. public class MyClassA { // Public nested class. public class MyClassB { } public static void Main(string[] args) { // Get the Type of the nested class. Type myTypeB = typeof(MyClassA.MyClassB); // Get the 'IsNestedPublic' property of the nested class // 'Type'. Console.WriteLine("\nThe nested class has the property 'IsNestedPublic' value: "+ myTypeB.IsNestedPublic.ToString()); } }
public bool IsNotPublic {get;}
|
TypeAttributes.VisibilityMask selects the visibility attributes.
using System; using System.IO; using System.Reflection; class MyMemberInfo { public static void Main(string[] args) { Console.WriteLine ("\nReflection.MemberInfo"); //Get the Type and MemberInfo Type MyType =Type.GetType("System.IO.File"); MemberInfo[] Mymemberinfoarray = MyType.GetMembers(); //Get and display the DeclaringType method Console.WriteLine("\nThere are {0} members in {1}.", Mymemberinfoarray.Length, MyType.FullName); Console.WriteLine("Is {0} public? {1}", MyType.FullName, MyType.IsPublic.ToString()); } }
This code produces the following output:
There are 27 members in System.IO.File.
Is System.IO.File public? False
The following code example demonstrates why you cannot use IsPublic and IsNotPublic for nested classes.
public class A { public class B { } private class C { } }
For nested classes, ignore the results of IsPublic and IsNotPublic and pay attention only to the results of IsNestedPublic and IsNestedPrivate. The reflection output for this code fragment would be as follows:
Class | IsNotPublic | IsPublic | IsNestedPublic | IsNestedPrivate |
---|---|---|---|---|
A | FALSE | TRUE | FALSE | FALSE |
B | FALSE | FALSE | TRUE | FALSE |
C | FALSE | FALSE | FALSE | TRUE |
public bool IsPointer {get;}
|
public bool IsPrimitive {get;}
|
// Check if the types are primitive datatypes. Console.WriteLine ("'{0}' is a primitive datatype : {1} ", typeof(int).Name, typeof(int).IsPrimitive); Console.WriteLine ("'{0}' is a primitive datatype : {1} ", typeof(string).Name, typeof(string).IsPrimitive);
public bool IsPublic {get;}
|
TypeAttributes.VisibilityMask selects the visibility attributes.
using System; using System.IO; using System.Reflection; class MyMemberInfo { public static void Main(string[] args) { Console.WriteLine ("\nReflection.MemberInfo"); //Get the Type and MemberInfo Type MyType =Type.GetType("System.IO.File"); MemberInfo[] Mymemberinfoarray = MyType.GetMembers(); //Get and display the DeclaringType method Console.WriteLine("\nThere are {0} members in {1}.", Mymemberinfoarray.Length, MyType.FullName); Console.WriteLine("Is {0} public? {1}", MyType.FullName, MyType.IsPublic.ToString()); } }
This code produces the following output:
There are 27 members in System.IO.File.
Is System.IO.File public? True
The following code example demonstrates why you cannot use IsPublic and IsNotPublic for nested classes.
public class A { public class B { } private class C { } }
For nested classes, ignore the results of IsPublic and IsNotPublic and pay attention only to the results of IsNestedPublic and IsNestedPrivate. The reflection output for this code fragment would be as follows:
Class | IsNotPublic | IsPublic | IsNestedPublic | IsNestedPrivate |
---|---|---|---|---|
A | FALSE | TRUE | FALSE | FALSE |
B | FALSE | FALSE | TRUE | FALSE |
C | FALSE | FALSE | FALSE | TRUE |
public bool IsSealed {get;}
|
// Declare class 'MyTestClass' as sealed. sealed public class MyTestClass { } public static void Main(string []args) { try { bool myBool = false; MyTestClass myTestClassInstance = new MyTestClass(); // Get Type of 'myTestClassInstance'. Type myType = myTestClassInstance.GetType(); // Get the 'IsSealed' property of the 'MyTestClass' instance. myBool = myType.IsSealed; Console.WriteLine("\n{0} class is Sealed: {1}.",myType.FullName,myBool.ToString ()); } catch (Exception e) { Console.WriteLine("\nThe following exception is raised: {0}",e.Message); } }
public bool IsSerializable {get;}
|
// Declare a class as public with [Serializable] attribute. [Serializable] public class MyTestClass { } public static void Main(string []args) { try { bool myBool = false; MyTestClass myTestClassInstance = new MyTestClass(); // Get Type of 'myTestClassInstance'. Type myType = myTestClassInstance.GetType(); // Get the 'IsSerializable' property of the 'MyTestClass' instance. myBool = myType.IsSerializable; Console.WriteLine("\n{0} class is Serializable: {1}.",myType.FullName,myBool.ToString ()); } catch (Exception e) { Console.WriteLine("\nThe following exception is raised: {0}",e.Message); } }
public bool IsSpecialName {get;}
|
private void DumpMethods(Type aType) { if (!ShowMethods) return; MethodInfo[] mInfo = aType.GetMethods(); myWriter.WriteLine("Methods"); bool found = false; if (mInfo.Length != 0) { for ( int i=0; i < mInfo.Length; i++ ) { // Only display methods declared in this type. Also // filter out any methods with special names, because these // cannot be generally called by the user. That is, their // functionality is usually exposed in other ways, for example, // property get/set methods are exposed as properties. if (mInfo[i].DeclaringType == aType && !mInfo[i].IsSpecialName) { found = true; StringBuilder modifiers = new StringBuilder(); if (mInfo[i].IsStatic) {modifiers.Append("static ");} if (mInfo[i].IsPublic) {modifiers.Append("public ");} if (mInfo[i].IsFamily) {modifiers.Append("protected ");} if (mInfo[i].IsAssembly) {modifiers.Append("internal ");} if (mInfo[i].IsPrivate) {modifiers.Append("private ");} myWriter.WriteLine("{0} {1}", modifiers, mInfo[i]); } } } if (!found) { myWriter.WriteLine("(none)"); } }
public bool IsUnicodeClass {get;}
|
public bool IsValueType {get;}
|
This property returns true for enumerations, but not for the Enum type itself, which is a class. For an example that demonstrates this behavior, see Type.IsEnum.
This property is read-only.
// Declare enum type. enum MyEnum { One, Two } public static void Main(string []args) { try { bool myBool = false; MyEnum myTestEnum = MyEnum.One; // Get Type of 'myTestEnum'. Type myType = myTestEnum.GetType(); // Get the 'IsValueType' property of the 'MyTestEnum' // of variable. myBool = myType.IsValueType; Console.WriteLine("\n {0} is value type: {1}.",myType.FullName,myBool.ToString()); } catch (Exception e) { Console.WriteLine("\nThe following exception is raised: {0}",e.Message); } }
public override MemberTypes MemberType {get;}
|
MemberInfo[] others = t.GetMember(mi.Name, mi.MemberType, BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Instance);
public override Module Module {get;}
|
public override string Name {get;}
|
public override string Namespace {get;}
|
public override Type ReflectedType {get;}
|
public override RuntimeTypeHandle TypeHandle {get;}
|
Exception Type | Condition |
---|---|
NotSupportedException | This property is not currently supported. |
Use this handle to access the underlying metadata handle.
public ConstructorInfo TypeInitializer {get;}
|
public TypeToken TypeToken {get;}
|
public FieldBuilder UnderlyingField {get;}
|
public override Type UnderlyingSystemType {get;}
|
public Type CreateType(); |
Exception Type | Condition |
---|---|
InvalidOperationException | This type has been previously created. -or- The enclosing type has not been created. |
public FieldBuilder DefineLiteral( |
literalName
literalValue
o
using System; using System.Reflection; class EqType { public static void Main(String[] args) { Type a = typeof(EqType); Type b = typeof(Type); Console.WriteLine("{0}", a.Equals(b).ToString()); b = (new EqType()).GetType(); Console.WriteLine("{0}", a.Equals(b).ToString()); } } //This code produces the following output: //False //True
o
using System; using System.Reflection; class EqType { public static void Main(String[] args) { int a = 1; float b = 1; Console.WriteLine("{0}", a.Equals(b).ToString()); b=a; Console.WriteLine("{0}", a.Equals(b).ToString()); } } //This code produces the following output: //False //False
~EnumBuilder(); |
public virtual Type[] FindInterfaces( |
filter
filterCriteria
-or-
An empty array of type Type, if no interfaces matching the filter are implemented or inherited by the current Type.
Exception Type | Condition |
---|---|
ArgumentNullException | filter is null. |
TargetInvocationException | A static initializer is invoked and throws an exception. |
The Module.FilterTypeName and Module.FilterTypeNameIgnoreCase delegates supplied by the Module class may also be used, in lieu of the TypeFilter delegate.
All of the interfaces implemented by this class are considered during the search, whether declared by a base class or this class itself.
This method searches the base class hierarchy, returning each of the matching interfaces each class implements as well as all the matching interfaces each of those interfaces implements (that is, the transitive closure of the matching interfaces is returned). No duplicate interfaces are returned.
using System; using System.Xml; using System.Reflection; public class MyFindInterfacesSample { public static void Main() { try { XmlDocument myXMLDoc = new XmlDocument(); myXMLDoc.LoadXml("<book genre='novel' ISBN='1-861001-57-5'>" + "<title>Pride And Prejudice</title>" + "</book>"); Type myType = myXMLDoc.GetType(); // Specify the TypeFilter delegate that compares the interfaces against filter criteria. TypeFilter myFilter = new TypeFilter(MyInterfaceFilter); String[] myInterfaceList = new String[2] {"System.Collections.IEnumerable", "System.Collections.ICollection"}; for(int index=0; index < myInterfaceList.Length; index++) { Type[] myInterfaces = myType.FindInterfaces(myFilter, myInterfaceList[index]); if (myInterfaces.Length > 0) { Console.WriteLine("\nThe {0} implements the interface {1}", myType, myInterfaceList[index]); for(int j =0;j < myInterfaces.Length;j++) Console.WriteLine("Interfaces supported #{0} : {1}",j,myInterfaces[j].ToString()); } else Console.WriteLine("\nThe {0} does not implement the interface {1}",myType,myInterfaceList[index]); } } catch(ArgumentNullException e) { Console.WriteLine("ArgumentNullException : " + e.Message); } catch(TargetInvocationException e) { Console.WriteLine("TargetInvocationException : " + e.Message); } catch(Exception e) { Console.WriteLine("Exception : " + e.Message); } } public static bool MyInterfaceFilter(Type typeObj,Object criteriaObj) { if(typeObj.ToString() == criteriaObj.ToString()) return true; else return false; } }
public virtual MemberInfo[] FindMembers( |
memberType
bindingAttr
-or-
Zero, to return null.
A bitmask comprised of one or more BindingFlags that specify how the search is conducted.-or-
Zero, to return null.
filter
filterCriteria
The fields of FieldAttributes, MethodAttributes, and MethodImplAttributes can be used in conjunction with the FilterAttribute delegate supplied by this class.
The search criteria that determines whether a member is returned in the array of MemberInfo objects.The fields of FieldAttributes, MethodAttributes, and MethodImplAttributes can be used in conjunction with the FilterAttribute delegate supplied by this class.
-or-
An empty array of type MemberInfo, if the current Type does not have members of type memberType that match the filter criteria.
Exception Type | Condition |
---|---|
ArgumentNullException | filter is null. |
Members include properties, methods, fields, events, and so on. If the requested type is non-public and the caller does not have ReflectionPermission to reflect non-public objects outside the current assembly, this method returns null.
The following BindingFlags filter flags can be used to define which members to include in the search:
The following BindingFlags modifier flags can be used to change how the search works:
See BindingFlags for more information.
Valid values for MemberType are defined in MemberInfo. If no such members are found, an empty array is returned.
Class initializers are available through Type.GetMember, Type.GetMembers, Type.FindMembers, and Type.GetConstructors.
public virtual int GetArrayRank(); |
Exception Type | Condition |
---|---|
NotSupportedException | The functionality of this method is unsupported in the base class and must be implemented in a derived class instead. |
ArgumentException | The current Type is not an array. |
using System; class MyArrayRankSample { public static void Main() { try { int[,,] myArray = new int[,,] {{{12,2,35},{300,78,33}},{{92,42,135},{30,7,3}}}; Type myType = myArray.GetType(); Console.WriteLine("Contents of myArray: {{{12,2,35},{300,78,33}},{{92,42,135},{30,7,3}}}"); Console.WriteLine("The rank for myArray is: {0}", myType.GetArrayRank()); } catch(NotSupportedException e) { Console.WriteLine("NotSupportedException raised."); Console.WriteLine("Source: " + e.Source); Console.WriteLine("Message: " + e.Message); } catch(Exception e) { Console.WriteLine("Exception raised."); Console.WriteLine("Source: " + e.Source); Console.WriteLine("Message: " + e.Message); } } }
protected override TypeAttributes GetAttributeFlagsImpl(); |
public ConstructorInfo GetConstructor( |
types
-or-
An empty array of the type Type to get a constructor that takes no parameters.
-or-
An array of Type objects representing the number, order, and type of the parameters for the constructor to get.-or-
An empty array of the type Type to get a constructor that takes no parameters.
-or-
Exception Type | Condition |
---|---|
ArgumentNullException | types is null. -or- One of the elements in types is null. |
ArgumentException | types is multidimensional. |
If the requested type is non-public and the caller does not have ReflectionPermission to reflect non-public objects outside the current assembly, this method returns null.
using System; using System.Reflection; using System.Security; public class MyClass1 { public MyClass1(){} public MyClass1(int i){} public static void Main() { try { Type myType = typeof(MyClass1); Type[] types = new Type[1]; types[0] = typeof(int); // Get the constructor that takes an integer as a parameter. ConstructorInfo constructorInfoObj = myType.GetConstructor(types); if (constructorInfoObj != null) { Console.WriteLine("The constructor of the class MyClass1 that takes an " + "integer as a parameter is: "); Console.WriteLine(constructorInfoObj.ToString()); } else { Console.WriteLine("The constructor of the class MyClass1 that takes an integer " + "as a parameter is not available."); } } catch(Exception e) { Console.WriteLine("Exception caught."); Console.WriteLine("Source: " + e.Source); Console.WriteLine("Message: " + e.Message); } } }
public ConstructorInfo GetConstructor( |
bindingAttr
-or-
Zero, to return null.
A bitmask comprised of one or more BindingFlags that specify how the search is conducted.-or-
Zero, to return null.
binder
-or-
null, to use the Type.DefaultBinder.
A Binder object that defines a set of properties and enables binding, which can involve selection of an overloaded method, coercion of argument types, and invocation of a member through reflection.-or-
null, to use the Type.DefaultBinder.
types
-or-
An empty array of the type Type (that is, Type[] types = new Type[0]) to get a constructor that takes no parameters.
-or-
An array of Type objects representing the number, order, and type of the parameters for the constructor to get.-or-
An empty array of the type Type (that is, Type[] types = new Type[0]) to get a constructor that takes no parameters.
-or-
modifiers
Exception Type | Condition |
---|---|
ArgumentNullException | types is null. -or- One of the elements in types is null. |
ArgumentException | types is multidimensional. -or- modifiers is multidimensional. -or- types and modifiers do not have the same length. |
If an exact match does not exist, the binder will attempt to coerce the parameter types specified in the types array in order to select a match. If the binder is unable to select a match, then null is returned.
If the requested type is non-public and the caller does not have ReflectionPermission to reflect non-public objects outside the current assembly, this method returns null.
The following BindingFlags filter flags can be used to define which constructors to include in the search:
See BindingFlags for more information.
Type.GetConstructor cannot be used to obtain a class initializer. Class initializers are available through Type.GetMember, Type.GetMembers, Type.FindMembers, Type.GetConstructors, and Type.TypeInitializer.using System; using System.Reflection; using System.Security; public class MyClass1 { public MyClass1(int i){} public static void Main() { try { Type myType = typeof(MyClass1); Type[] types = new Type[1]; types[0] = typeof(int); // Get the constructor that is public and takes an integer parameter. ConstructorInfo constructorInfoObj = myType.GetConstructor( BindingFlags.Instance | BindingFlags.Public, null, types, null); if (constructorInfoObj != null ) { Console.WriteLine("The constructor of the MyClass1 class that is public " + "and takes an integer as a parameter is:"); Console.WriteLine(constructorInfoObj.ToString()); } else { Console.WriteLine("The constructor of the MyClass1 class that is public " + "and takes an integer as a parameter is not available."); } } catch(ArgumentNullException e) { Console.WriteLine("ArgumentNullException: " + e.Message); } catch(ArgumentException e) { Console.WriteLine("ArgumentException: " + e.Message); } catch(SecurityException e) { Console.WriteLine("SecurityException: " + e.Message); } catch(Exception e) { Console.WriteLine("Exception: " + e.Message); } } }
public ConstructorInfo GetConstructor( |
bindingAttr
-or-
Zero, to return null.
A bitmask comprised of one or more BindingFlags that specify how the search is conducted.-or-
Zero, to return null.
binder
-or-
null, to use the Type.DefaultBinder.
A Binder object that defines a set of properties and enables binding, which can involve selection of an overloaded method, coercion of argument types, and invocation of a member through reflection.-or-
null, to use the Type.DefaultBinder.
callConvention
types
-or-
An empty array of the type Type (that is, Type[] types = new Type[0]) to get a constructor that takes no parameters.
An array of Type objects representing the number, order, and type of the parameters for the constructor to get.-or-
An empty array of the type Type (that is, Type[] types = new Type[0]) to get a constructor that takes no parameters.
modifiers
Exception Type | Condition |
---|---|
ArgumentNullException | types is null. -or- One of the elements in types is null. |
ArgumentException | types is multidimensional. -or- modifiers is multidimensional. -or- types and modifiers do not have the same length. |
The types array and the modifiers array have the same length. A parameter specified in the types array can have the following attributes, which are specified in the modifiers array: pdIn, pdOut, pdLcid, pdRetval, pdOptional, and pdHasDefault, which represent [In], [Out], [lcid], [retval], [optional], and a value specifying whether the parameter has a default value. A parameter's associated attributes are stored in the metadata and enhance interoperability.
If an exact match does not exist, the binder will attempt to coerce the parameter types specified in the types array in order to select a match. If the binder is unable to select a match, then null is returned.
The following BindingFlags filter flags can be used to define which constructors to include in the search:
See BindingFlags for more information.
Type.GetConstructor cannot be used to obtain a class initializer. Class initializers are available through Type.GetMember, Type.GetMembers, Type.FindMembers, Type.GetConstructors, and Type.TypeInitializer.
If the requested type is non-public and the caller does not have ReflectionPermission to reflect non-public objects outside the current assembly, this method returns null.
The following table shows what members of a base class are returned by the Get methods when reflecting on a type.
Member Type | Static | Non-Static |
---|---|---|
Constructor | No | No |
Field | No | Yes. A field is always hide-by-name-and-signature. |
Event | Not applicable | The common type system rule is that the inheritance is the same as that of the methods that implement the property. Reflection treats properties as hide-by-name-and-signature. See note 2 below. |
Method | No | Yes. A method (both virtual and non-virtual) can be hide-by-name or hide-by-name-and-signature. |
Nested Type | No | No |
Property | Not applicable | The common type system rule is that the inheritance is the same as that of the methods that implement the property. Reflection treats properties as hide-by-name-and-signature. See note 2 below. |
using System; using System.Reflection; using System.Security; public class MyClass1 { public MyClass1(int i){} public static void Main() { try { Type myType = typeof(MyClass1); Type[] types = new Type[1]; types[0] = typeof(int); // Get the constructor that is public, instance method and takes an integer parameter. ConstructorInfo constructorInfoObj = myType.GetConstructor( BindingFlags.Instance | BindingFlags.Public, null, CallingConventions.HasThis, types, null); if(constructorInfoObj != null) { Console.WriteLine("The constructor of the class MyClass1 that is a public " + "instance method and takes an integer as a parameter is: "); Console.WriteLine(constructorInfoObj.ToString()); } else { Console.WriteLine("The Constructor of the class 'MyClass1' that is a public instance " + "method and takes an integer as a parameter is not available."); } } catch(ArgumentNullException e) { Console.WriteLine("ArgumentNullException: " + e.Message); } catch(ArgumentException e) { Console.WriteLine("ArgumentException: " + e.Message); } catch(SecurityException e) { Console.WriteLine("SecurityException: " + e.Message); } catch(Exception e) { Console.WriteLine("Exception: " + e.Message); } } }
protected override ConstructorInfo GetConstructorImpl( |
bindingAttr
-or-
Zero, to conduct a case-sensitive search for public methods.
A bitmask comprised of one or more BindingFlags that specify how the search is conducted.-or-
Zero, to conduct a case-sensitive search for public methods.
binder
-or-
null, to use the Type.DefaultBinder.
A Binder object that defines a set of properties and enables binding, which can involve selection of an overloaded method, coercion of argument types, and invocation of a member through reflection.-or-
null, to use the Type.DefaultBinder.
callConvention
types
-or-
An empty array of the type Type (that is, Type[] types = new Type[0]) to get a constructor that takes no parameters.
An array of Type objects representing the number, order, and type of the parameters for the constructor to get.-or-
An empty array of the type Type (that is, Type[] types = new Type[0]) to get a constructor that takes no parameters.
modifiers
Exception Type | Condition |
---|---|
NotSupportedException | This method is not currently supported in types that are not complete. |
public ConstructorInfo[] GetConstructors(); |
-or-
An empty array of type ConstructorInfo, if no public constructors are defined for the current Type.
Member Type | Static | Non-Static |
---|---|---|
Constructor | No | No |
Field | No | Yes. A field is always hide-by-name-and-signature. |
Event | Not applicable | The common type system rule is that the inheritance is the same as that of the methods that implement the property. Reflection treats properties as hide-by-name-and-signature. See note 2 below. |
Method | No | Yes. A method (both virtual and non-virtual) can be hide-by-name or hide-by-name-and-signature. |
Nested Type | No | No |
Property | Not applicable | The common type system rule is that the inheritance is the same as that of the methods that implement the property. Reflection treats properties as hide-by-name-and-signature. See note 2 below. |
This method calls GetConstructors. It will not find static constructors unless you explicitly pass BindingFlags.Static, as shown in the examples.
Class initializers are available through Type.GetMember, Type.GetMembers, Type.FindMembers, and Type.GetConstructors.
using System; using System.Reflection; public class t { public t() {} static t() {} public t(int i) {} public static void Main() { ConstructorInfo[] p = typeof(t).GetConstructors(); Console.WriteLine(p.Length); for (int i=0;i<p.Length;i++) { Console.WriteLine(p[i].IsStatic); } } }
The output of this code is:
2
False
False
Because GetConstructors () only calls the Public and Instance BindingFlags, the static constructor is neither counted by the for expression nor evaluated by IsStatic.
Use GetConstructors (BindingFlags) and pass it BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Instance to find static constructors, as follows:
using System; using System.Reflection; public class t { public t() {} static t() {} public t(int i) {} public static void Main() { ConstructorInfo[] p = typeof(t).GetConstructors( BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Instance); Console.WriteLine(p.Length); for (int i=0;i<p.Length;i++) { Console.WriteLine(p[i].IsStatic); } } }
Now the output is:
3
False
True
False
public override ConstructorInfo[] GetConstructors( |
bindingAttr
Exception Type | Condition |
---|---|
NotSupportedException | This method is not currently supported in types that are not complete. |
inherit
Exception Type | Condition |
---|---|
NotSupportedException | This method is not currently supported in types that are not complete. |
attributeType
inherit
Exception Type | Condition |
---|---|
NotSupportedException | This method is not currently supported in types that are not complete. |
public virtual MemberInfo[] GetDefaultMembers(); |
-or-
An empty array of type MemberInfo, if the current Type does not have default members.
Members include properties, methods, fields, events, and so on.
The following table shows what members of a base class are returned by the Get methods when reflecting on a type.
Member Type | Static | Non-Static |
---|---|---|
Constructor | No | No |
Field | No | Yes. A field is always hide-by-name-and-signature. |
Event | Not applicable | The common type system rule is that the inheritance is the same as that of the methods that implement the property. Reflection treats properties as hide-by-name-and-signature. See note 2 below. |
Method | No | Yes. A method (both virtual and non-virtual) can be hide-by-name or hide-by-name-and-signature. |
Nested Type | No | No |
Property | Not applicable | The common type system rule is that the inheritance is the same as that of the methods that implement the property. Reflection treats properties as hide-by-name-and-signature. See note 2 below. |
using System; using System.Reflection; using System.IO; [DefaultMemberAttribute("Age")] public class MyClass { public void Name(String s) {} public int Age { get { return 20; } } public static void Main() { try { Type myType = typeof(MyClass); MemberInfo[] memberInfoArray = myType.GetDefaultMembers(); if (memberInfoArray.Length > 0) { Console.WriteLine("The default members of the class MyClass are:\n"); foreach(MemberInfo memberInfoObj in memberInfoArray) { Console.WriteLine("The default member name is: " + memberInfoObj.ToString()); } } else { Console.WriteLine("No default members are available."); } } catch(InvalidOperationException e) { Console.WriteLine("InvalidOperationException: " + e.Message); } catch(IOException e) { Console.WriteLine("IOException: " + e.Message); } catch(Exception e) { Console.WriteLine("Exception: " + e.Message); } } }
public override Type GetElementType(); |
Exception Type | Condition |
---|---|
NotSupportedException | This method is not currently supported. |
name
Exception Type | Condition |
---|---|
ArgumentNullException | name is null. |
If the requested type is non-public and the caller does not have ReflectionPermission to reflect non-public objects outside the current assembly, this method returns null.
The following table shows what members of a base class are returned by the Get methods when reflecting on a type.
Member Type | Static | Non-Static |
---|---|---|
Constructor | No | No |
Field | No | Yes. A field is always hide-by-name-and-signature. |
Event | Not applicable | The common type system rule is that the inheritance is the same as that of the methods that implement the property. Reflection treats properties as hide-by-name-and-signature. See note 2 below. |
Method | No | Yes. A method (both virtual and non-virtual) can be hide-by-name or hide-by-name-and-signature. |
Nested Type | No | No |
Property | Not applicable | The common type system rule is that the inheritance is the same as that of the methods that implement the property. Reflection treats properties as hide-by-name-and-signature. See note 2 below. |
Type myType = typeof(System.Windows.Forms.Button); EventInfo myEvent = myType.GetEvent("Click"); if(myEvent != null) { Console.WriteLine("Looking for Click event in Button class."); Console.WriteLine(myEvent.ToString()); } else Console.WriteLine("The Click event is not available with Button class");
public override EventInfo GetEvent( |
name
bindingAttr
Exception Type | Condition |
---|---|
NotSupportedException | This method is not currently supported in types that are not complete. |
public override EventInfo[] GetEvents(); |
Exception Type | Condition |
---|---|
NotSupportedException | This method is not currently supported in types that are not complete. |
public override EventInfo[] GetEvents( |
bindingAttr
Exception Type | Condition |
---|---|
NotSupportedException | This method is not currently supported in types that are not complete. |
name
Exception Type | Condition |
---|---|
ArgumentNullException | name is null. |
If the requested type is non-public and the caller does not have ReflectionPermission to reflect non-public objects outside the current assembly, this method returns null.
public class MyFieldClassA { public string field = "A Field"; public string Field { get { return field; } set { if(field!=value) { field=value; } } } } public class MyFieldClassB { public string field = "B Field"; public string Field { get { return field; } set { if(field!=value) { field=value; } } } } public class MyFieldInfoClass { public static void Main() { try { MyFieldClassB myFieldObjectB = new MyFieldClassB(); MyFieldClassA myFieldObjectA = new MyFieldClassA(); Type myTypeA = Type.GetType("MyFieldClassA"); FieldInfo myFieldInfo = myTypeA.GetField("field"); Type myTypeB = Type.GetType("MyFieldClassB"); FieldInfo myFieldInfo1 = myTypeB.GetField("field", BindingFlags.Public | BindingFlags.Instance); Console.WriteLine("The value of the field is : {0} ", myFieldInfo.GetValue(myFieldObjectA)); Console.WriteLine("The value of the field is : {0} ", myFieldInfo1.GetValue(myFieldObjectB)); } catch(SecurityException e) { Console.WriteLine("Exception Raised !"); Console.WriteLine("Message :"+e.Message); } catch(ArgumentNullException e) { Console.WriteLine("Exception Raised !"); Console.WriteLine("Message :"+e.Message); } catch(Exception e) { Console.WriteLine("Exception Raised !"); Console.WriteLine("Message :"+e.Message); } } }
public override FieldInfo GetField( |
name
bindingAttr
Exception Type | Condition |
---|---|
NotSupportedException | This method is not currently supported in types that are not complete. |
public FieldInfo[] GetFields(); |
-or-
An empty array of type FieldInfo, if no public fields are defined for the current Type.
Member Type | Static | Non-Static |
---|---|---|
Constructor | No | No |
Field | No | Yes. A field is always hide-by-name-and-signature. |
Event | Not applicable | The common type system rule is that the inheritance is the same as that of the methods that implement the property. Reflection treats properties as hide-by-name-and-signature. See note 2 below. |
Method | No | Yes. A method (both virtual and non-virtual) can be hide-by-name or hide-by-name-and-signature. |
Nested Type | No | No |
Property | Not applicable | The common type system rule is that the inheritance is the same as that of the methods that implement the property. Reflection treats properties as hide-by-name-and-signature. See note 2 below. |
Console.WriteLine("HashCode of the System.Windows.Forms.Button type is : {0}", typeof(System.Windows.Forms.Button).GetHashCode());
public override FieldInfo[] GetFields( |
bindingAttr
Exception Type | Condition |
---|---|
NotSupportedException | This method is not currently supported in types that are not complete. |
public override int GetHashCode(); |
Console.WriteLine("HashCode of the System.Windows.Forms.Button type is : {0}", typeof(System.Windows.Forms.Button).GetHashCode());
name
Exception Type | Condition |
---|---|
ArgumentNullException | name is null. |
TargetInvocationException | A static initializer is invoked and throws an exception. |
public static void Main() { Hashtable hashtableObj = new Hashtable(); Type objType = hashtableObj.GetType(); MemberInfo[] arrayMemberInfo; MethodInfo[] arrayMethodInfo; try { // Get the methods implemented in 'IDeserializationCallback' interface. arrayMethodInfo =objType.GetInterface("IDeserializationCallback").GetMethods(); Console.WriteLine ("\nMethods of 'IDeserializationCallback' Interface :"); for(int index=0;index < arrayMethodInfo.Length ;index++) Console.WriteLine (arrayMethodInfo[index].ToString() ); // Get FullName for interface by using Ignore case search. Console.WriteLine ("\nMethods of 'IEnumerable' Interface"); arrayMethodInfo = objType.GetInterface("ienumerable",true).GetMethods(); for(int index=0;index < arrayMethodInfo.Length ;index++) Console.WriteLine (arrayMethodInfo[index].ToString()); //Get the Interface methods for 'IDictionary' interface InterfaceMapping interfaceMappingObj; interfaceMappingObj = objType.GetInterfaceMap(typeof(IDictionary)); arrayMemberInfo = interfaceMappingObj.InterfaceMethods; Console.WriteLine ("\nHashtable class Implements the following IDictionary Interface methods :"); for(int index=0; index < arrayMemberInfo.Length; index++) Console.WriteLine (arrayMemberInfo[index].ToString() ); } catch (Exception e) { Console.WriteLine ("Exception : " + e.ToString()); } }
name
ignoreCase
Exception Type | Condition |
---|---|
NotSupportedException | This method is not currently supported in types that are not complete. |
public override InterfaceMapping GetInterfaceMap( |
interfaceType
Exception Type | Condition |
---|---|
ArgumentException | The type does not implement the interface. |
public override Type[] GetInterfaces(); |
public MemberInfo[] GetMember( |
name
Exception Type | Condition |
---|---|
ArgumentNullException | name is null. |
Members include properties, methods, fields, events, and so on.
This method searches the current classes and its base classes. Only public methods can be found using this method. If the requested type is non-public and the caller does not have ReflectionPermission to reflect non-public objects outside the current assembly, this method returns null.
Class initializers are available through Type.GetMember, Type.GetMembers, Type.FindMembers, and Type.GetConstructors.
The following table shows what members of a base class are returned by the Get methods when reflecting on a type.
Member Type | Static | Non-Static |
---|---|---|
Constructor | No | No |
Field | No | Yes. A field is always hide-by-name-and-signature. |
Event | Not applicable | The common type system rule is that the inheritance is the same as that of the methods that implement the property. Reflection treats properties as hide-by-name-and-signature. See note 2 below. |
Method | No | Yes. A method (both virtual and non-virtual) can be hide-by-name or hide-by-name-and-signature. |
Nested Type | No | No |
Property | Not applicable | The common type system rule is that the inheritance is the same as that of the methods that implement the property. Reflection treats properties as hide-by-name-and-signature. See note 2 below. |
public void GetMemberInfo() { String myString = "GetMember_String"; Type myType = myString.GetType(); // Get the members for myString starting with 'C',using searchCriteria 'C*'. MemberInfo[] myMembers = myType.GetMember("C*"); if(myMembers.Length > 0) { Console.WriteLine("\nThe Member(s) starting with 'C' for type {0} :", myType); for(int index=0; index < myMembers.Length; index++) Console.WriteLine("Member {0} : {1}", index + 1, myMembers[index].ToString()); } else Console.WriteLine("No Members match the Search Criteria."); }
public virtual MemberInfo[] GetMember( |
name
bindingAttr
-or-
Zero, to return null.
A bitmask comprised of one or more BindingFlags that specify how the search is conducted.-or-
Zero, to return null.
Exception Type | Condition |
---|---|
ArgumentNullException | name is null. |
Members include properties, methods, fields, events, and so on.
This method searches the current classes and its base classes. If the requested member is non-public and the caller does not have ReflectionPermission to reflect non-public objects outside the current assembly, this method returns null.
The following BindingFlags filter flags can be used to define which members to include in the search:
The following BindingFlags modifier flags can be used to change how the search works:
See BindingFlags for more information.
Class initializers are available through Type.GetMember, Type.GetMembers, Type.FindMembers, and Type.GetConstructors.
public void GetPublicStaticMemberInfo() { String myString = "GetMember_String_BindingFlag"; Type myType = myString.GetType(); // Get the Public Static members for the class myString starting with 'C'. MemberInfo[] myMembers = myType.GetMember("C*", BindingFlags.Public |BindingFlags.Static); if(myMembers.Length > 0) { Console.WriteLine("\nThe Public Static Member(s) starting with 'C' for type {0} :",myType); for(int index=0; index < myMembers.Length; index++) Console.WriteLine("Member {0} : {1}", index + 1, myMembers[index].ToString()); } else Console.WriteLine("No Members match the Search Criteria."); }
public override MemberInfo[] GetMember( |
name
type
bindingAttr
Exception Type | Condition |
---|---|
NotSupportedException | This method is not currently supported in types that are not complete. |
public MemberInfo[] GetMembers(); |
-or-
An empty array of type MemberInfo, if the current Type does not have public members.
Class initializers are available through Type.GetMember, Type.GetMembers, Type.FindMembers, and Type.GetConstructors.
The following table shows what members of a base class are returned by the Get methods when reflecting on a type.
Member Type | Static | Non-Static |
---|---|---|
Constructor | No | No |
Field | No | Yes. A field is always hide-by-name-and-signature. |
Event | Not applicable | The common type system rule is that the inheritance is the same as that of the methods that implement the property. Reflection treats properties as hide-by-name-and-signature. See note 2 below. |
Method | No | Yes. A method (both virtual and non-virtual) can be hide-by-name or hide-by-name-and-signature. |
Nested Type | No | No |
Property | Not applicable | The common type system rule is that the inheritance is the same as that of the methods that implement the property. Reflection treats properties as hide-by-name-and-signature. See note 2 below. |
class MyClass { public int myInt = 0; public string myString = null; public MyClass() { } public void Myfunction() { } } class Type_GetMembers { public static void Main() { try { MyClass myObject = new MyClass(); MemberInfo[] myMemberInfo; // Get the type of 'MyClass'. Type myType = myObject.GetType(); // Get the information related to all public member's of 'MyClass'. myMemberInfo = myType.GetMembers(); Console.WriteLine( "\nThe members of class '{0}' are :\n", myType); for (int i =0 ; i < myMemberInfo.Length ; i++) { // Display name and type of the concerned member. Console.WriteLine( "'{0}' is a {1}", myMemberInfo[i].Name, myMemberInfo[i].MemberType); } } catch(SecurityException e) { Console.WriteLine("Exception : " + e.Message ); } } }
public override MemberInfo[] GetMembers( |
bindingAttr
Exception Type | Condition |
---|---|
NotSupportedException | This method is not currently supported in types that are not complete. |
public MethodInfo GetMethod( |
name
Exception Type | Condition |
---|---|
AmbiguousMatchException | More than one method is found with the specified name. |
ArgumentNullException | name is null. |
If the requested type is non-public and the caller does not have ReflectionPermission to reflect non-public objects outside the current assembly, this method returns null.
class MyClass { public int myInt = 0; public string myString = null; public MyClass() { } public void Myfunction(int i) { } } class Type_GetMethod { public static void Main() { try { MyClass MyObject = new MyClass(); MethodInfo myMethodInfo; // Get the type of the class 'MyClass'. Type myType = MyObject.GetType(); // Get the method information for a method named 'MyFunction'. myMethodInfo = myType.GetMethod("Myfunction"); // Get the parameters for the method 'Myfunction'. ParameterInfo[] myParameters = myMethodInfo.GetParameters(); Console.WriteLine( "\nThe parameters of the method 'Myfunction' of class 'MyClass' are :\n"); // Display the position and type of the parameters. for(int i = 0; i < myParameters.Length; i++) Console.WriteLine("The parameter {0} is of type {1}", myParameters[i].Position + 1, myParameters[i].ParameterType); } catch (SecurityException e) { Console.WriteLine("SecurityException : " + e.Message ); } catch (Exception e) { Console.WriteLine("Exception : " + e.Message ); } } }
public MethodInfo GetMethod( |
name
bindingAttr
-or-
Zero, to return null.
A bitmask comprised of one or more BindingFlags that specify how the search is conducted.-or-
Zero, to return null.
Exception Type | Condition |
---|---|
AmbiguousMatchException | More than one method is found with the specified name and matching the specified binding constraints. |
ArgumentNullException | name is null. |
The following BindingFlags modifier flags can be used to change how the search works:
See BindingFlags for more information.
If the requested type is non-public and the caller does not have ReflectionPermission to reflect non-public objects outside the current assembly, this method returns null.
class MyClass { public void MyMethod() { } } public class Type_GetMethod { public static void Main() { try { // Get the type of 'MyClass'. Type myType = typeof(MyClass); // Get the method information of the type 'MyClass'. MethodInfo myMethodInfo = myType.GetMethod("MyMethod", BindingFlags.Public|BindingFlags.Instance ); // Displays the member info to the console. Console.WriteLine("\nThe signature of 'MyMethod' is : {0}", myMethodInfo.ToString()); } catch(Exception e) { Console.WriteLine("Exception : {0}", e.Message); } } }
public MethodInfo GetMethod( |
name
types
-or-
An empty array of the type Type (that is, Type[] types = new Type[0]) to get a method that takes no parameters.
An array of Type objects representing the number, order, and type of the parameters for the method to get.-or-
An empty array of the type Type (that is, Type[] types = new Type[0]) to get a method that takes no parameters.
Exception Type | Condition |
---|---|
AmbiguousMatchException | More than one method is found with the specified name and specified parameters. |
ArgumentNullException | name is null. -or- types is null. -or- One of the elements in types is null. |
ArgumentException | types is multidimensional. -or- modifiers is multidimensional. -or- types and modifiers do not have the same length. |
If the requested type is non-public and the caller does not have ReflectionPermission to reflect non-public objects outside the current assembly, this method returns null.
// Get a 'Type' object corresponding to 'MyClass1' class. Type myClassType = typeof(MyClass1); // Create a Type array. Type[] typeArray =new Type[1]; typeArray.SetValue(typeof(int),0); // Find the method matching the specified argument types. MethodInfo myMethodInfo = myClassType.GetMethod("MyMethod",typeArray); Console.WriteLine("The Name of the Method :"+myMethodInfo);
public MethodInfo GetMethod( |
name
types
-or-
An empty array of the type Type (that is, Type[] types = new Type[0]) to get a method that takes no parameters.
An array of Type objects representing the number, order, and type of the parameters for the method to get.-or-
An empty array of the type Type (that is, Type[] types = new Type[0]) to get a method that takes no parameters.
modifiers
Exception Type | Condition |
---|---|
AmbiguousMatchException | More than one method is found with the specified name and specified parameters. |
ArgumentNullException | name is null. -or- types is null. -or- One of the elements in types is null. |
ArgumentException | types is multidimensional. -or- modifiers is multidimensional. -or- types and modifiers do not have the same length. |
The types array and the modifiers array have the same length. A parameter specified in the types array can have the following attributes, which are specified in the modifiers array: pdIn, pdOut, pdLcid, pdRetval, pdOptional, and pdHasDefault, which represent [In], [Out], [lcid], [retval], [optional], and a value specifying whether the parameter has a default value. A parameter's associated attributes are stored in the metadata and are used for interoperability.
The search for name is case-sensitive.
If the requested type is non-public and the caller does not have ReflectionPermission to reflect non-public objects outside the current assembly, this method returns null.
public MethodInfo GetMethod( |
name
bindingAttr
-or-
Zero, to return null.
A bitmask comprised of one or more BindingFlags that specify how the search is conducted.-or-
Zero, to return null.
binder
-or-
null, to use the Type.DefaultBinder.
A Binder object that defines a set of properties and enables binding, which can involve selection of an overloaded method, coercion of argument types, and invocation of a member through reflection.-or-
null, to use the Type.DefaultBinder.
types
-or-
An empty array of the type Type (that is, Type[] types = new Type[0]) to get a method that takes no parameters.
An array of Type objects representing the number, order, and type of the parameters for the method to get.-or-
An empty array of the type Type (that is, Type[] types = new Type[0]) to get a method that takes no parameters.
modifiers
Exception Type | Condition |
---|---|
AmbiguousMatchException | More than one method is found with the specified name and matching the specified binding constraints. |
ArgumentNullException | name is null. -or- types is null. -or- One of the elements in types is null. |
ArgumentException | types is multidimensional. -or- modifiers is multidimensional. -or- types and modifiers do not have the same length. |
The types array and the modifiers array have the same length. A parameter specified in the types array can have the following attributes, which are specified in the modifiers array: pdIn, pdOut, pdLcid, pdRetval, pdOptional, and pdHasDefault, which represent [In], [Out], [lcid], [retval], [optional], and a value specifying whether the parameter has a default value. A parameter's associated attributes are stored in the metadata and enhance interoperability.
The following BindingFlags filter flags can be used to define which methods to include in the search:
The following BindingFlags modifier flags can be used to change how the search works:
See BindingFlags for more information.
If the requested type is non-public and the caller does not have ReflectionPermission to reflect non-public objects outside the current assembly, this method returns null.
public class MyClass { public int i = 10; public string k = "My Field"; public int MyMethod(int i) { this.i = i; return i; } public string MyMethod(string k) { this.k = k; return k; } } public class Type_GetMethod { public static void Main() { try { // Get the type of the class 'MyClass'. Type myType = typeof(MyClass); // Get the attributes of the method and the metadata of the method 'MyMethod'. MethodInfo myMethodInfo = myType.GetMethod("MyMethod", BindingFlags.Public | BindingFlags.Instance, null, new Type[] {typeof(int)}, null); Console.WriteLine("\n Declaring type of the method '{0}' is : \n '{1}'", myMethodInfo, myMethodInfo.DeclaringType); // Get the attributes of the method and the metadata of the method 'MyMethod'. MethodInfo myMethodInfo1 = myType.GetMethod("MyMethod", BindingFlags.Public | BindingFlags.Instance, null, new Type[] {typeof(string)}, null); Console.WriteLine("\n Declaring type of the method '{0}' is : \n '{1}'", myMethodInfo1, myMethodInfo1.DeclaringType); } catch(Exception e) { Console.WriteLine("Exception : {0}", e.Message); } } }
public MethodInfo GetMethod( |
name
bindingAttr
-or-
Zero, to return null.
A bitmask comprised of one or more BindingFlags that specify how the search is conducted.-or-
Zero, to return null.
binder
-or-
null, to use the Type.DefaultBinder.
A Binder object that defines a set of properties and enables binding, which can involve selection of an overloaded method, coercion of argument types, and invocation of a member through reflection.-or-
null, to use the Type.DefaultBinder.
callConvention
types
-or-
An empty array of the type Type (that is, Type[] types = new Type[0]) to get a method that takes no parameters.
An array of Type objects representing the number, order, and type of the parameters for the method to get.-or-
An empty array of the type Type (that is, Type[] types = new Type[0]) to get a method that takes no parameters.
modifiers
Exception Type | Condition |
---|---|
AmbiguousMatchException | More than one method is found with the specified name and matching the specified binding constraints. |
ArgumentNullException | name is null. -or- types is null. -or- One of the elements in types is null. |
ArgumentException | types is multidimensional. -or- modifiers is multidimensional. -or- types and modifiers do not have the same length. |
The following table shows what members of a base class are returned by the GetXXX methods when reflecting on a type.
Member Type | Static | Non-Static |
---|---|---|
Constructor | No | No |
Field | No | Yes. A field is always hide-by-name-and-signature. |
Event | Not applicable | The common type system rule is that the inheritance is the same as that of the methods that implement the property. Reflection treats properties as hide-by-name-and-signature. See note 2 below. |
Method | No | Yes. A method (both virtual and non-virtual) can be hide-by-name or hide-by-name-and-signature. |
Nested Type | No | No |
Property | Not applicable | The common type system rule is that the inheritance is the same as that of the methods that implement the property. Reflection treats properties as hide-by-name-and-signature. See note 2 below. |
The types array and the modifiers array have the same length. A parameter specified in the types array can have the following attributes, which are specified in the modifiers array: pdIn, pdOut, pdLcid, pdRetval, pdOptional, and pdHasDefault, which represent [In], [Out], [lcid], [retval], [optional], and a value specifying whether the parameter has a default value. A parameter's associated attributes are stored in the metadata and enhance interoperability.
The following BindingFlags filter flags can be used to define which methods to include in the search:
The following BindingFlags modifier flags can be used to change how the search works:
See BindingFlags for more information.
If the requested type is non-public and the caller does not have ReflectionPermission to reflect non-public objects outside the current assembly, this method returns null.
public class MyClass { public int i = 10; public int j = 2; public int MyFunc(int i , int j) { int k; k = i * 10 - j; return k; } } public class Type_GetMethod { public static void Main() { try { // Get the type of the class 'MyClass'. Type myType = typeof(MyClass); // Get the method information of 'MyFunc(int , int )'. MemberInfo myMemberInfo = myType.GetMethod("MyFunc", BindingFlags.Public | BindingFlags.Instance, null, CallingConventions.Any, new Type[] {typeof(int),typeof(int)}, null); Console.WriteLine("\nDisplaying method 'MyFunc' : \n"); // Print the method information to the console. Console.WriteLine("{0}", myMemberInfo); } catch(Exception e) { Console.WriteLine("Exception : {0}", e.Message); } } }
protected override MethodInfo GetMethodImpl( |
name
bindingAttr
-or-
Zero, to conduct a case-sensitive search for public methods.
A bitmask comprised of one or more BindingFlags that specify how the search is conducted.-or-
Zero, to conduct a case-sensitive search for public methods.
binder
-or-
null, to use the Type.DefaultBinder.
A Binder object that defines a set of properties and enables binding, which can involve selection of an overloaded method, coercion of argument types, and invocation of a member through reflection.-or-
null, to use the Type.DefaultBinder.
callConvention
types
-or-
An empty array of the type Type (that is, Type[] types = new Type[0]) to get a method that takes no parameters.
An array of Type objects representing the number, order, and type of the parameters for the method to get.-or-
An empty array of the type Type (that is, Type[] types = new Type[0]) to get a method that takes no parameters.
modifiers
Exception Type | Condition |
---|---|
NotSupportedException | This method is not currently supported in types that are not complete. |
public MethodInfo[] GetMethods(); |
-or-
An empty array of type MethodInfo, if no public methods are defined for the current Type.
Member Type | Static | Non-Static |
---|---|---|
Constructor | No | No |
Field | No | Yes. A field is always hide-by-name-and-signature. |
Event | Not applicable | The common type system rule is that the inheritance is the same as that of the methods that implement the property. Reflection treats properties as hide-by-name-and-signature. See note 2 below. |
Method | No | Yes. A method (both virtual and non-virtual) can be hide-by-name or hide-by-name-and-signature. |
Nested Type | No | No |
Property | Not applicable | The common type system rule is that the inheritance is the same as that of the methods that implement the property. Reflection treats properties as hide-by-name-and-signature. See note 2 below. |
public override MethodInfo[] GetMethods( |
bindingAttr
Exception Type | Condition |
---|---|
NotSupportedException | This method is not currently supported in types that are not complete. |
name
Exception Type | Condition |
---|---|
ArgumentNullException | name is null. |
The following table shows what members of a base class are returned by the Get methods when reflecting on a type.
Member Type | Static | Non-Static |
---|---|---|
Constructor | No | No |
Field | No | Yes. A field is always hide-by-name-and-signature. |
Event | Not applicable | The common type system rule is that the inheritance is the same as that of the methods that implement the property. Reflection treats properties as hide-by-name-and-signature. See note 2 below. |
Method | No | Yes. A method (both virtual and non-virtual) can be hide-by-name or hide-by-name-and-signature. |
Nested Type | No | No |
Property | Not applicable | The common type system rule is that the inheritance is the same as that of the methods that implement the property. Reflection treats properties as hide-by-name-and-signature. See note 2 below. |
public override Type GetNestedType( |
name
bindingAttr
-or-
Zero, to conduct a case-sensitive search for public methods.
A bitmask comprised of one or more BindingFlags that specify how the search is conducted.-or-
Zero, to conduct a case-sensitive search for public methods.
Exception Type | Condition |
---|---|
NotSupportedException | This method is not currently supported in types that are not complete. |
public Type[] GetNestedTypes(); |
-or-
An empty array of type Type, if no types are nested within the current Type.Member Type | Static | Non-Static |
---|---|---|
Constructor | No | No |
Field | No | Yes. A field is always hide-by-name-and-signature. |
Event | Not applicable | The common type system rule is that the inheritance is the same as that of the methods that implement the property. Reflection treats properties as hide-by-name-and-signature. See note 2 below. |
Method | No | Yes. A method (both virtual and non-virtual) can be hide-by-name or hide-by-name-and-signature. |
Nested Type | No | No |
Property | Not applicable | The common type system rule is that the inheritance is the same as that of the methods that implement the property. Reflection treats properties as hide-by-name-and-signature. See note 2 below. |
// Get Type Object corresponding to MyClass. Type myType=typeof(MyClass); // Get array of nested type objects which are in 'MyClass'. Type[] nestType=myType.GetNestedTypes(); Console.WriteLine("Number of nested types are {0}",nestType.Length); foreach(Type t in nestType) Console.WriteLine("Nested type is {0}",t.ToString());
public override Type[] GetNestedTypes( |
bindingAttr
An empty array of type Type, if no types are nested within the current Type, or if none of the nested types match the binding constraints.
Exception Type | Condition |
---|---|
NotSupportedException | This method is not currently supported in types that are not complete. |
public PropertyInfo[] GetProperties(); |
-or-
An empty array of type PropertyInfo, if the current Type does not have public properties.
Member Type | Static | Non-Static |
---|---|---|
Constructor | No | No |
Field | No | Yes. A field is always hide-by-name-and-signature. |
Event | Not applicable | The common type system rule is that the inheritance is the same as that of the methods that implement the property. Reflection treats properties as hide-by-name-and-signature. See note 2 below. |
Method | No | Yes. A method (both virtual and non-virtual) can be hide-by-name or hide-by-name-and-signature. |
Nested Type | No | No |
Property | Not applicable | The common type system rule is that the inheritance is the same as that of the methods that implement the property. Reflection treats properties as hide-by-name-and-signature. See note 2 below. |
PropertyInfo[] myPropertyInfo; // Get the properties of 'Type' class object. myPropertyInfo = Type.GetType("System.Type").GetProperties(); Console.WriteLine("Properties of System.Type are:"); for (int i = 0; i < myPropertyInfo.Length; i++) { Console.WriteLine(myPropertyInfo[i].ToString()); }
public override PropertyInfo[] GetProperties( |
bindingAttr
Exception Type | Condition |
---|---|
NotSupportedException | This method is not currently supported in types that are not complete. |
public PropertyInfo GetProperty( |
name
Exception Type | Condition |
---|---|
AmbiguousMatchException | More than one property is found with the specified name. |
ArgumentNullException | name is null. |
If the requested type is non-public and the caller does not have ReflectionPermission to reflect non-public objects outside the current assembly, this method returns null.
// Get Type Object corresponding to MyClass. Type myType=typeof(MyClass); // Get PropertyInfo object by passing property name. PropertyInfo myPropInfo = myType.GetProperty("MyProperty"); // Display Name propety to console. Console.WriteLine("The Property {0} exists",myPropInfo.Name); }
Internally, this property is referred to by the name "Item" in the metadata. Therefore, any attempt to get PropertyInfo using reflection must specify this internal name in order for the PropertyInfo to be returned correctly.
public PropertyInfo GetProperty( |
name
bindingAttr
-or-
Zero, to return null.
A bitmask comprised of one or more BindingFlags that specify how the search is conducted.-or-
Zero, to return null.
Exception Type | Condition |
---|---|
AmbiguousMatchException | More than one property is found with the specified name and matching the specified binding constraints. |
ArgumentNullException | name is null. |
The following BindingFlags filter flags can be used to define which properties to include in the search:
The following BindingFlags modifier flags can be used to change how the search works:
See BindingFlags for more information.
If the requested type is non-public and the caller does not have ReflectionPermission to reflect non-public objects outside the current assembly, this method returns null.
// Get Type Object corresponding to MyClass. Type myType=typeof(MyClass); // Get PropertyInfo object by passing property name and specifying BindingFlags. PropertyInfo myPropInfo = myType.GetProperty("MyProperty", BindingFlags.Public| BindingFlags.Instance); // Display Name propety to console. Console.WriteLine("{0} is a Property of 'MyClass'.",myPropInfo.Name); }
Internally, this property is referred to by the name "Item" in the metadata. Therefore, any attempt to get PropertyInfo using reflection must specify this internal name in order for the PropertyInfo to be returned correctly.
public PropertyInfo GetProperty( |
name
returnType
Exception Type | Condition |
---|---|
AmbiguousMatchException | More than one property is found with the specified name. |
ArgumentNullException | name is null. |
If the requested type is non-public and the caller does not have ReflectionPermission to reflect non-public objects outside the current assembly, this method returns null.
Type myType = typeof(MyClass1); // Get the 'PropertyInfo' object representing 'MyProperty1' property. PropertyInfo myStringProperties1 = myType.GetProperty("MyProperty1", typeof(string)); Console.WriteLine("The Name of the first Property of MyClass1 :"+myStringProperties1.Name); Console.WriteLine("The Type of first Property of MyClass1 :"+myStringProperties1.PropertyType); // Get a 'Type' array corresponding to the indexed property. Type[] myTypeArr = new Type[2]; myTypeArr.SetValue(typeof(int),0); myTypeArr.SetValue(typeof(int),1); // Get the 'PropertyInfo' object representing 'MyProperty2' property. PropertyInfo myStringProperties2 =myType.GetProperty("Item",typeof(int),myTypeArr); Console.WriteLine("{0} property exists in MyClass1.",myStringProperties2.ToString()); Console.WriteLine("The Name of the second Property of MyClass1 :"+myStringProperties2.Name); Console.WriteLine("The Type of second Property of MyClass1 :"+myStringProperties2.PropertyType);
Internally, this property is referred to by the name "Item" in the metadata. Therefore, any attempt to get PropertyInfo using reflection must specify this internal name in order for the PropertyInfo to be returned correctly.
public PropertyInfo GetProperty( |
name
types
-or-
An empty array of the type Type (that is, Type[] types = new Type[0]) to get a property that is not indexed.
An array of Type objects representing the number, order, and type of the parameters for the indexed property to get.-or-
An empty array of the type Type (that is, Type[] types = new Type[0]) to get a property that is not indexed.
Exception Type | Condition |
---|---|
AmbiguousMatchException | More than one property is found with the specified name and matching the specified argument types. |
ArgumentNullException | name is null. -or- types is null. -or- One of the elements in types is null. |
ArgumentException | types is multidimensional. |
If the requested type is non-public and the caller does not have ReflectionPermission to reflect non-public objects outside the current assembly, this method returns null.
// Get Type Object. Type myType=typeof(MyClass1); Type[] myTypeArr = new Type[2]; // Initialize Type array. myTypeArr.SetValue(typeof(int),0); myTypeArr.SetValue(typeof(int),1); // Get PropertyInfo object for indexed property 'Item' which has two integer parameters. PropertyInfo myPropInfo = myType.GetProperty("Item",myTypeArr); // Dispaly propety to console. Console.WriteLine("{0} property exists in MyClass1.",myPropInfo.ToString());
Internally, this property is referred to by the name "Item" in the metadata. Therefore, any attempt to get PropertyInfo using reflection must specify this internal name in order for the PropertyInfo to be returned correctly.
public PropertyInfo GetProperty( |
name
returnType
types
-or-
An empty array of the type Type (that is, Type[] types = new Type[0]) to get a property that is not indexed.
An array of Type objects representing the number, order, and type of the parameters for the indexed property to get.-or-
An empty array of the type Type (that is, Type[] types = new Type[0]) to get a property that is not indexed.
Exception Type | Condition |
---|---|
AmbiguousMatchException | More than one property is found with the specified name and matching the specified argument types. |
ArgumentNullException | name is null. -or- types is null. -or- One of the elements in types is null. |
ArgumentException | types is multidimensional. |
If the requested type is non-public and the caller does not have ReflectionPermission to reflect non-public objects outside the current assembly, this method returns null.
public PropertyInfo GetProperty( |
name
returnType
types
-or-
An empty array of the type Type (that is, Type[] types = new Type[0]) to get a property that is not indexed.
An array of Type objects representing the number, order, and type of the parameters for the indexed property to get.-or-
An empty array of the type Type (that is, Type[] types = new Type[0]) to get a property that is not indexed.
modifiers
Exception Type | Condition |
---|---|
AmbiguousMatchException | More than one property is found with the specified name and matching the specified argument types and modifiers. |
ArgumentNullException | name is null. -or- types is null. -or- One of the elements in types is null. |
ArgumentException | types is multidimensional. -or- modifiers is multidimensional. -or- types and modifiers do not have the same length. |
The types array and the modifiers array have the same length. A parameter specified in the types array can have the following attributes, which are specified in the modifiers array: pdIn, pdOut, pdLcid, pdRetval, pdOptional, and pdHasDefault, which represent [In], [Out], [lcid], [retval], [optional], and a value specifying whether the parameter has a default value. A parameter's associated attributes are stored in the metadata and enhance interoperability.
The search for name is case-sensitive.
If the requested type is non-public and the caller does not have ReflectionPermission to reflect non-public objects outside the current assembly, this method returns null.
// MyPropAA - ReadOnly protected short m_prvPropAA = -1; public short m_PropAA = -2; public short this [Boolean nonPublic] { //get accessor for property {short MyPropAA} get { return ((nonPublic) ? m_prvPropAA: m_PropAA); } }
Internally, this property is referred to by the name "Item" in the metadata. Therefore, any attempt to get PropertyInfo using reflection must specify this internal name in order for the PropertyInfo to be returned correctly.
public PropertyInfo GetProperty( |
name
bindingAttr
-or-
Zero, to return null.
A bitmask comprised of one or more BindingFlags that specify how the search is conducted.-or-
Zero, to return null.
binder
-or-
null, to use the Type.DefaultBinder.
A Binder object that defines a set of properties and enables binding, which can involve selection of an overloaded method, coercion of argument types, and invocation of a member through reflection.-or-
null, to use the Type.DefaultBinder.
returnType
types
-or-
An empty array of the type Type (that is, Type[] types = new Type[0]) to get a property that is not indexed.
An array of Type objects representing the number, order, and type of the parameters for the indexed property to get.-or-
An empty array of the type Type (that is, Type[] types = new Type[0]) to get a property that is not indexed.
modifiers
Exception Type | Condition |
---|---|
AmbiguousMatchException | More than one property is found with the specified name and matching the specified binding constraints. |
ArgumentNullException | name is null. -or- types is null. -or- One of the elements in types is null. |
ArgumentException | types is multidimensional. -or- modifiers is multidimensional. -or- types and modifiers do not have the same length. |
The following table shows what members of a base class are returned by the Get methods when reflecting on a type.
Member Type | Static | Non-Static |
---|---|---|
Constructor | No | No |
Field | No | Yes. A field is always hide-by-name-and-signature. |
Event | Not applicable | The common type system rule is that the inheritance is the same as that of the methods that implement the property. Reflection treats properties as hide-by-name-and-signature. See note 2 below. |
Method | No | Yes. A method (both virtual and non-virtual) can be hide-by-name or hide-by-name-and-signature. |
Nested Type | No | No |
Property | Not applicable | The common type system rule is that the inheritance is the same as that of the methods that implement the property. Reflection treats properties as hide-by-name-and-signature. See note 2 below. |
The types array and the modifiers array have the same length. A parameter specified in the types array can have the following attributes, which are specified in the modifiers array: pdIn, pdOut, pdLcid, pdRetval, pdOptional, and pdHasDefault, which represent [In], [Out], [lcid], [retval], [optional], and a value specifying whether the parameter has a default value. A parameter's associated attributes are stored in the metadata and enhance interoperability.
The following BindingFlags filter flags can be used to define which properties to include in the search:
The following BindingFlags modifier flags can be used to change how the search works:
See BindingFlags for more information.
If the requested type is non-public and the caller does not have ReflectionPermission to reflect non-public objects outside the current assembly, this method returns null.
Internally, this property is referred to by the name "Item" in the metadata. Therefore, any attempt to get PropertyInfo using reflection must specify this internal name in order for the PropertyInfo to be returned correctly.
protected override PropertyInfo GetPropertyImpl( |
name
bindingAttr
-or-
Zero, to conduct a case-sensitive search for public properties.
A bitmask comprised of one or more BindingFlags that specify how the search is conducted.-or-
Zero, to conduct a case-sensitive search for public properties.
binder
-or-
null, to use the Type.DefaultBinder.
A Binder object that defines a set of properties and enables binding, which can involve selection of an overloaded member, coercion of argument types, and invocation of a member through reflection.-or-
null, to use the Type.DefaultBinder.
returnType
types
-or-
An empty array of the type Type (that is, Type[] types = new Type[0]) to get a property that is not indexed.
An array of Type objects representing the number, order, and type of the parameters for the indexed property to get.-or-
An empty array of the type Type (that is, Type[] types = new Type[0]) to get a property that is not indexed.
modifiers
Exception Type | Condition |
---|---|
NotSupportedException | This method is not currently supported in types that are not complete. |
public Type GetType(); |
protected override bool HasElementTypeImpl(); |
Exception Type | Condition |
---|---|
NotSupportedException | This method is not supported. |
public object InvokeMember( |
name
An empty string ("") to invoke the default member.
-or-An empty string ("") to invoke the default member.
invokeAttr
binder
-or-
null, to use the Type.DefaultBinder.
A Binder object that defines a set of properties and enables binding, which can involve selection of an overloaded method, coercion of argument types, and invocation of a member through reflection.-or-
null, to use the Type.DefaultBinder.
target
args
Exception Type | Condition |
---|---|
ArgumentNullException | invokeAttr contains CreateInstance and typeName is null. |
ArgumentException | args is multidimensional. -or- invokeAttr is not a valid BindingFlags attribute. -or- invokeAttr contains CreateInstance combined with InvokeMethod, GetField, SetField, GetProperty, or SetProperty. -or- invokeAttr contains both GetField and SetField. -or- invokeAttr contains both GetProperty and SetProperty. -or- invokeAttr contains InvokeMethod combined with SetField or SetProperty. -or- invokeAttr contains SetField and args has more than one element. -or- This method is called on a COM object and one of the following binding flags was not passed in: BindingFlags.InvokeMethod, BindingFlags.GetProperty, BindingFlags.SetProperty, BindingFlags.PutDispProperty, or BindingFlags.PutRefDispProperty. -or- One of the named parameter arrays contains a string that is null. |
MemberAccessException | The specified member is a class initializer. |
MissingFieldException | The field or property cannot be found. |
MissingMethodException | The method cannot be found. |
SecurityException | The specified member is non-public and the caller does not have ReflectionPermission to reflect non-public members outside the current assembly. |
TargetException | The specified member cannot be invoked on target. |
AmbiguousMatchException | More than one method matches the binding criteria. |
The following BindingFlags modifier flags can be used to change how the search works:
The following BindingFlags invocation flags can be used to denote what action to take with the member:
See BindingFlags for more information.
A method will be invoked if the following conditions are true:
After the method is selected, it is invoked. Accessibility is checked at that point. The search may control which set of methods are searched based upon the accessibility attribute associated with the method. The Binder.BindToMethod method of the Binder class is responsible for selecting the method to be invoked. The default binder selects the most specific match.
Access restrictions are ignored for fully trusted code; that is, private constructors, methods, fields, and properties can be accessed and invoked through System.Reflection whenever the code is fully trusted.
You can use Type.InvokeMember to set a field to a particular value by specifying BindingFlags.SetField. For example, if you want to set a public instance field named F on class C, and F is a String you can say:
typeof(C).InvokeMember( "F",
BindingFlags.SetField, null, C, new Object{ "strings new value"}, null, null,
null );
Now suppose that F is a String[] you can say:
typeof(C).InvokeMember( "F",
BindingFlags.SetField, null, C, new Object{new String[]{"a","z","c","d"}, null,
null, null );
which will initialize the field F to this new array. Furthermore you can use Type.InvokeMember to set a position in an array by supplying to the index of the value and then the next value by doing the following:
typeof(C).InvokeMember( "F",
BindingFlags.SetField, null, C, new Object{1, "b"}, null, null, null );
This will change string "z" in the array that F holds to string "b".
using System; using System.IO; using System.Reflection; public class Sample { public void Method() { //Call a static method Type t = typeof (TestClass); t.InvokeMember ("SayHello", BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.Static, null, null, new object [] {}); //Call an instance method TestClass c = new TestClass (); c.GetType().InvokeMember ("AddUp", BindingFlags.Public | BindingFlags.InvokeMethod, null, c, new object [] {}); c.GetType().InvokeMember ("AddUp", BindingFlags.Public | BindingFlags.InvokeMethod, null, c, new object [] {}); //Call a method with arguments object [] args = new object [] {100.09, 184.45}; object result; result = t.InvokeMember ("ComputeSum", BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.Static, null, null, args); Console.WriteLine ("{0} + {1} = {2}", args[0], args[1], result); //Get a field value result = t.InvokeMember ("Name", BindingFlags.Public | BindingFlags.GetField, null, c, new object [] {}); Console.WriteLine ("Name == {0}", result); //Set a field t.InvokeMember ("Name", BindingFlags.Public |BindingFlags.SetField, null, c, new object [] {"NewName"}); result = t.InvokeMember ("Name", BindingFlags.Public |BindingFlags.GetField, null, c, new object [] {}); Console.WriteLine ("Name == {0}", result); //Get an indexed property value int index = 3; result = t.InvokeMember ("Item", BindingFlags.Public |BindingFlags.GetProperty , null, c, new object [] {index}); Console.WriteLine ("Item[{0}] == {1}", index, result); //Set an indexed property value index = 3; t.InvokeMember ("Item", BindingFlags.Public |BindingFlags.SetProperty, null, c, new object [] {index, "NewValue"}); result = t.InvokeMember ("Item", BindingFlags.Public |BindingFlags.GetProperty , null, c, new object [] {index}); Console.WriteLine ("Item[{0}] == {1}", index, result); //Get a field or property result = t.InvokeMember ("Name", BindingFlags.Public |BindingFlags.GetField | BindingFlags.GetProperty, null, c, new object [] {}); Console.WriteLine ("Name == {0}", result); result = t.InvokeMember ("Value", BindingFlags.Public |BindingFlags.GetField | BindingFlags.GetProperty, null, c, new object [] {}); Console.WriteLine ("Value == {0}", result); //Call a method using named arguments object[] argValues = new object [] {"Mouse", "Micky"}; String [] argNames = new String [] {"lastName", "firstName"}; t.InvokeMember ("PrintName", BindingFlags.Public |BindingFlags.InvokeMethod, null, null, argValues, null, null, argNames); //Call the default member of a type Type t3 = typeof (TestClass2); t3.InvokeMember ("", BindingFlags.Public |BindingFlags.InvokeMethod, null, new TestClass2(), new object [] {}); //Invoking a ByRef member 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]); Console.WriteLine ("\r\nPress Return to exit."); Console.Read(); } } // Class added so sample will compile public class TestClass {} // Class added so sample will compile public class TestClass2 {}
public object InvokeMember( |
name
-or-
An empty string ("") to invoke the default member.
The String containing the name of the constructor, method, property, or field member to invoke.-or-
An empty string ("") to invoke the default member.
invokeAttr
binder
-or-
null, to use the Type.DefaultBinder.
A Binder object that defines a set of properties and enables binding, which can involve selection of an overloaded method, coercion of argument types, and invocation of a member through reflection.-or-
null, to use the Type.DefaultBinder.
target
args
culture
-or-
null to use the current thread's CultureInfo.
The CultureInfo object representing the globalization locale to use, which may be necessary for locale-specific conversions, such as converting a numeric String to a Double.-or-
null to use the current thread's CultureInfo.
Exception Type | Condition |
---|---|
ArgumentNullException | invokeAttr contains CreateInstance and typeName is null. |
ArgumentException | args is multidimensional. -or- invokeAttr is not a valid BindingFlags attribute. -or- invokeAttr contains CreateInstance combined with InvokeMethod, GetField, SetField, GetProperty, or SetProperty. -or- invokeAttr contains both GetField and SetField. -or- invokeAttr contains both GetProperty and SetProperty. -or- invokeAttr contains InvokeMethod combined with SetField or SetProperty. -or- invokeAttr contains SetField and args has more than one element. -or- This method is called on a COM object and one of the following binding flags was not passed in: BindingFlags.InvokeMethod, BindingFlags.GetProperty, BindingFlags.SetProperty, BindingFlags.PutDispProperty, or BindingFlags.PutRefDispProperty. -or- One of the named parameter arrays contains a string that is null. |
MemberAccessException | The specified member is a class initializer. |
MissingFieldException | The field or property cannot be found. |
MissingMethodException | The method cannot be found. |
SecurityException | The specified member is non-public and the caller does not have ReflectionPermission to reflect non-public members outside the current assembly. |
TargetException | The specified member cannot be invoked on target. |
AmbiguousMatchException | More than one method matches the binding criteria. |
The following BindingFlags filter flags can be used to define which members to include in the search:
The following BindingFlags modifier flags can be used to change how the search works:
The following BindingFlags invocation flags can be used to denote what action to take with the member:
See BindingFlags for more information.
A method will be invoked if the following conditions are true:
After the method is selected, it is invoked. Accessibility is checked at that point. The search may control which set of methods are searched based upon the accessibility attribute associated with the method. The Binder.BindToMethod method of the Binder class is responsible for selecting the method to be invoked. The default binder selects the most specific match.
Access restrictions are ignored for fully trusted code; that is, private constructors, methods, fields, and properties can be accessed and invoked through Reflection whenever the code is fully trusted.
You can use Type.InvokeMember to set a field to a particular value by specifying BindingFlags.SetField. For example, if you want to set a public instance field named F on class C, and F is a String you can say:
typeof(C).InvokeMember( "F",
BindingFlags.SetField, null, C, new Object{ "strings new value"}, null, null,
null );
Now suppose that F is a String[] you can say:
typeof(C).InvokeMember( "F",
BindingFlags.SetField, null, C, new Object{new String[]{"a","z","c","d"}, null,
null, null );
which will initialize the field F to this new array. Furthermore you can use Type.InvokeMember to set a position in an array by supplying to the index of the value and then the next value by doing the following:
typeof(C).InvokeMember( "F",
BindingFlags.SetField, null, C, new Object{1, "b"}, null, null, null );
This will change string "z" in the array that F holds to string "b".
using System; using System.IO; using System.Reflection; public class Sample { public void Method() { //Call a static method Type t = typeof (TestClass); t.InvokeMember ("SayHello", BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.Static, null, null, new object [] {}); //Call an instance method TestClass c = new TestClass (); c.GetType().InvokeMember ("AddUp", BindingFlags.Public | BindingFlags.InvokeMethod, null, c, new object [] {}); c.GetType().InvokeMember ("AddUp", BindingFlags.Public | BindingFlags.InvokeMethod, null, c, new object [] {}); //Call a method with arguments object [] args = new object [] {100.09, 184.45}; object result; result = t.InvokeMember ("ComputeSum", BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.Static, null, null, args); Console.WriteLine ("{0} + {1} = {2}", args[0], args[1], result); //Get a field value result = t.InvokeMember ("Name", BindingFlags.Public | BindingFlags.GetField, null, c, new object [] {}); Console.WriteLine ("Name == {0}", result); //Set a field t.InvokeMember ("Name", BindingFlags.Public |BindingFlags.SetField, null, c, new object [] {"NewName"}); result = t.InvokeMember ("Name", BindingFlags.Public |BindingFlags.GetField, null, c, new object [] {}); Console.WriteLine ("Name == {0}", result); //Get an indexed property value int index = 3; result = t.InvokeMember ("Item", BindingFlags.Public |BindingFlags.GetProperty , null, c, new object [] {index}); Console.WriteLine ("Item[{0}] == {1}", index, result); //Set an indexed property value index = 3; t.InvokeMember ("Item", BindingFlags.Public |BindingFlags.SetProperty, null, c, new object [] {index, "NewValue"}); result = t.InvokeMember ("Item", BindingFlags.Public |BindingFlags.GetProperty , null, c, new object [] {index}); Console.WriteLine ("Item[{0}] == {1}", index, result); //Get a field or property result = t.InvokeMember ("Name", BindingFlags.Public |BindingFlags.GetField | BindingFlags.GetProperty, null, c, new object [] {}); Console.WriteLine ("Name == {0}", result); result = t.InvokeMember ("Value", BindingFlags.Public |BindingFlags.GetField | BindingFlags.GetProperty, null, c, new object [] {}); Console.WriteLine ("Value == {0}", result); //Call a method using named arguments object[] argValues = new object [] {"Mouse", "Micky"}; String [] argNames = new String [] {"lastName", "firstName"}; t.InvokeMember ("PrintName", BindingFlags.Public |BindingFlags.InvokeMethod, null, null, argValues, null, null, argNames); //Call the default member of a type Type t3 = typeof (TestClass2); t3.InvokeMember ("", BindingFlags.Public |BindingFlags.InvokeMethod, null, new TestClass2(), new object [] {}); //Invoking a ByRef member 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]); Console.WriteLine ("\r\nPress Return to exit."); Console.Read(); } } // Class added so sample will compile public class TestClass {} // Class added so sample will compile public class TestClass2 {}
public override object InvokeMember( |
name
invokeAttr
binder
target
args
modifiers
culture
namedParameters
Exception Type | Condition |
---|---|
NotSupportedException | This method is not currently supported in types that are not complete. |
protected override bool IsArrayImpl(); |
c
Determine the element types of a Type using Type.GetElementType.
using System; class ArrayTypeTest { public static void Main() { int i = 1; int [] array10 = new int [10]; int [] array2 = new int[2]; int [,]array22 = new int[2,2]; int [,]array24 = new int[2,4]; int [,,]array333 = new int[3,3,3]; Type array10Type = array10.GetType(); Type array2Type = array2.GetType(); Type array22Type = array22.GetType(); Type array24Type = array24.GetType(); Type array333Type = array333.GetType(); // If X and Y are not both arrays, then return false. Console.WriteLine("int[2] is assignable from int? {0} ", array2Type.IsAssignableFrom(i.GetType())); // If X and Y have same type and rank, then return true. Console.WriteLine("int[2] is assignable from int[10]? {0} ", array2Type.IsAssignableFrom(array10Type)); Console.WriteLine("int[2,2] is assignable from int[2,4]? {0}", array22Type.IsAssignableFrom(array24Type)); Console.WriteLine("int[2,4] is assignable from int[2,2]? {0}", array24Type.IsAssignableFrom(array22Type)); Console.WriteLine(""); // If X and Y do not have the same rank, then return false. Console.WriteLine("int[2,2] is assignable from int[10]? {0}", array22Type.IsAssignableFrom(array10Type)); Console.WriteLine("int[2,2] is assignable from int[3,3,3]? {0}", array22Type.IsAssignableFrom(array333Type)); Console.WriteLine("int[3,3,3] is assignable from int[2,2]? {0}", array333Type.IsAssignableFrom(array22Type)); } }
This code produces the following output:
int[2] is assignable from int? False int[2] is assignable from int[10]? True int[2,2] is assignable from int[2,4]? True int[2,4] is assignable from int[2,2]? True int[2,2] is assignable from int[10]? False int[2,2] is assignable from int[3,3,3]? False int[3,3,3] is assignable from int[2,2]? False
protected override bool IsByRefImpl(); |
protected override bool IsCOMObjectImpl(); |
protected virtual bool IsContextfulImpl(); |
A context intercepts calls to the class members and enforce policies that are applied to the class, such as synchronization.
public class MyTypeDelegatorClass : TypeDelegator { public string myElementType = null; private Type myType = null ; public MyTypeDelegatorClass(Type myType) : base(myType) { this.myType = myType; } // Override 'IsContextfulImpl' method of 'Type' class. protected override bool IsContextfulImpl() { // Check whether the type is contextful. if(myType.IsContextful) { myElementType = " is contextful "; return true; } return false; } } public class MyTypeDemoClass { public static void Main() { try { MyTypeDelegatorClass myType; Console.WriteLine ("Check whether 'MyContextBoundClass' can be hosted in a context."); // Check if 'MyContextBoundClass' type is contextful. myType = new MyTypeDelegatorClass(typeof(MyContextBoundClass)); if( myType.IsContextful) { Console.WriteLine(typeof(MyContextBoundClass) + " can be hosted in a context."); } else { Console.WriteLine(typeof(MyContextBoundClass) + " cannot be hosted in a context."); } // Check if 'int' type is contextful. myType = new MyTypeDelegatorClass(typeof(MyTypeDemoClass)); Console.WriteLine ("\nCheck whether 'MyTypeDemoClass' can be hosted in a context."); if( myType.IsContextful) { Console.WriteLine(typeof(MyTypeDemoClass) + " can be hosted in a context."); } else { Console.WriteLine(typeof(MyTypeDemoClass) + " cannot be hosted in a context."); } } catch( Exception e ) { Console.WriteLine("Exception: {0}", e.Message); } } } // This class is used to demonstrate 'IsContextfulImpl' method. public class MyContextBoundClass : ContextBoundObject { public string myString = "This class is used to demonstrate members of the 'Type' class."; }
attributeType
inherit
Exception Type | Condition |
---|---|
NotSupportedException | This method is not currently supported in types that are not complete. |
o
using System; public interface IMyIfc {} public class MyClass : IMyIfc {} public class MyDerivedClass : MyClass {} class IsInstanceTest { public static void Main() { Type imyifcType=typeof(IMyIfc); MyClass mc = new MyClass(); Type mcType = mc.GetType(); MyClass mdc = new MyDerivedClass(); Type mdcType = mdc.GetType(); int [] array = new int [10]; Type arrayType = typeof(Array); Console.WriteLine("int[] is instance of Array? {0}", arrayType.IsInstanceOfType(array)); Console.WriteLine("myclass instance is instance of MyClass? {0}", mcType.IsInstanceOfType(mc)); Console.WriteLine("myderivedclass instance is instance of MyClass? {0}", mcType.IsInstanceOfType(mdc)); Console.WriteLine("myclass instance is instance of IMyIfc? {0}", imyifcType.IsInstanceOfType(mc)); Console.WriteLine("myderivedclass instance is instance of IMyIfc? {0}", imyifcType.IsInstanceOfType(mdc)); } }
This code produces the following output:
int[] is instance of Array? True myclass instance is instance of MyClass? True myderivedclass instance is instance of MyClass? True myclass instance is instance of IMyIfc? True myderivedclass instance is instance of IMyIfc? True
protected virtual bool IsMarshalByRefImpl(); |
public class MyTypeDelegatorClass : TypeDelegator { public string myElementType = null; private Type myType = null ; public MyTypeDelegatorClass(Type myType) : base(myType) { this.myType = myType; } // Override 'IsMarshalByRefImpl' method of 'Type' class. protected override bool IsMarshalByRefImpl() { // Check whether the type is marshalled by reference. if(myType.IsMarshalByRef) { myElementType = " marshalled by reference"; return true; } return false; } } public class MyTypeDemoClass { public static void Main() { try { MyTypeDelegatorClass myType; Console.WriteLine ("Check whether 'MyContextBoundClass' is marshalled by reference"); // Check if 'MyContextBoundClass' type is marshalled by reference. myType = new MyTypeDelegatorClass(typeof(MyContextBoundClass)); if( myType.IsMarshalByRef ) { Console.WriteLine(typeof(MyContextBoundClass) + " is marshalled by reference."); } else { Console.WriteLine(typeof(MyContextBoundClass) + " is not marshalled by reference."); } // Check if 'int' type is marshalled by reference. myType = new MyTypeDelegatorClass(typeof(int)); Console.WriteLine ("\nCheck whether 'int' is marshalled by reference"); if( myType.IsMarshalByRef) { Console.WriteLine(typeof(int) + " is marshalled by reference."); } else { Console.WriteLine(typeof(int) + " is not marshalled by reference."); } } catch( Exception e ) { Console.WriteLine("Exception: {0}", e.Message); } } } // This class is used to demonstrate 'IsMarshalByRefImpl' method. public class MyContextBoundClass : ContextBoundObject { public string myString = "This class is used demonstrate members of the 'Type' class."; }
protected override bool IsPointerImpl(); |
protected override bool IsPrimitiveImpl(); |
c
using System; public interface IMyIfc {} public interface IDerived : IMyIfc {} public class Class1 : IMyIfc {} public class MyDerivedClass : Class1 {} class IsSubclassTest { public static void Main() { Type imyifcType = typeof(IMyIfc); Type imyderivedType = typeof(IDerived); Class1 mc = new Class1(); Type mcType = mc.GetType(); Class1 mdc = new MyDerivedClass(); Type mdcType = mdc.GetType(); int [] array = new int [10]; Type arrayOfIntsType = array.GetType(); Type arrayType = typeof(Array); Console.WriteLine("Array is derived class of int[]? {0}", arrayType.IsSubclassOf(arrayOfIntsType)); Console.WriteLine("int [] is derived class of Array? {0}", arrayOfIntsType.IsSubclassOf(arrayType)); Console.WriteLine("IMyIfc is derived class of IDerived? {0}", imyifcType.IsSubclassOf(imyderivedType)); Console.WriteLine("myclass is derived class of Class1? {0}", mcType.IsSubclassOf(mcType)); Console.WriteLine("myderivedclass is derived class of Class1? {0}", mdcType.IsSubclassOf(mcType)); } }
This code produces the following output:
Array is derived class of int[]? False int [] is derived class of Array? True IMyIfc is derived class of IDerived? False myclass is derived class of Class1? False myderivedclass is derived class of Class1? True
protected override bool IsValueTypeImpl(); |
protected object MemberwiseClone(); |
public void SetCustomAttribute( |
customBuilder
Exception Type | Condition |
---|---|
ArgumentNullException | con is null. |
public void SetCustomAttribute( |
con
binaryAttribute
Exception Type | Condition |
---|---|
ArgumentNullException | con or binaryAttribute is null. |
public override string ToString(); |
(long)0.Type().ToString()
returns "System.Int64" instead of merely "Int64".namespace MyNamespace { class MyClass { } } public class Type_ToString_3 { public static void Main() { try { Type myType = typeof(MyNamespace.MyClass); Console.WriteLine("\nPrinting the details of '{0}'\n", myType); // Get the namespace of the class 'Type_ToString_3'. Console.WriteLine("Namespace : {0}", myType.Namespace); // Get the name of the module. Console.WriteLine("Module : {0} ",myType.Module); // Get fully qualified common language runtime namespace. Console.WriteLine("Fully Qualified type : {0}", myType.ToString()); } catch(Exception e) { Console.WriteLine("Exception : " + e.Message ); } } }