[Serializable] |
This class is the primary way to access metadata, and it acts as a gateway to the Reflection API. Use the members of Type to get information about a type declaration, such as the constructors, methods, fields, properties, and events of a class, as well as the module and the assembly in which the class is deployed.
A Type object that represents a type is unique; that is, two Type object references refer to the same object if and only if they represent the same type. This allows for the synchronization of multiple static method invocations and for comparison of Type objects using reference equality.
This class is thread safe; multiple threads can concurrently read from or write to an instance of this type. An instance of Type can represent any of the following types:
A reference to the Type object associated with a type can be obtained in the following ways.
Delimiter | Separates names in the namespace of the Type. This field is read-only. |
EmptyTypes | Represents an empty array of type Type. This field is read-only. |
FilterAttribute | Represents the member filter used on attributes. This field is read-only. |
FilterName | Represents the case-sensitive member filter used on names. This field is read-only. |
FilterNameIgnoreCase | Represents the case-insensitive member filter used on names. This field is read-only. |
Missing | Represents a missing value in the Type information. This field is read-only. |
Assembly | Read-only Gets the Assembly that the type is declared in. |
AssemblyQualifiedName | Read-only Gets the fully qualified name of the Type, including the name of the assembly from which the Type was loaded. |
Attributes | Read-only Gets the attributes associated with the Type. |
BaseType | Read-only Gets the type from which the current Type directly inherits. |
DeclaringType | Read-only Overridden: Gets the class that declares this member. |
DefaultBinder | Read-only Gets the default binder used by the system. |
FullName | Read-only Gets the fully qualified name of the Type, including the namespace of the Type. |
GUID | Read-only Gets the GUID associated with the Type. |
HasElementType | Read-only 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 | Read-only Gets a value indicating whether the Type is abstract and must be overridden. |
IsAnsiClass | Read-only Gets a value indicating whether the string format attribute AnsiClass is selected for the Type. |
IsArray | Read-only Gets a value indicating whether the Type is an array. |
IsAutoClass | Read-only Gets a value indicating whether the string format attribute AutoClass is selected for the Type. |
IsAutoLayout | Read-only Gets a value indicating whether the class layout attribute AutoLayout is selected for the Type. |
IsByRef | Read-only Gets a value indicating whether the Type is passed by reference. |
IsClass | Read-only Gets a value indicating whether the Type is a class; that is, not a value type or interface. |
IsCOMObject | Read-only Gets a value indicating whether the Type is a COM object. |
IsContextful | Read-only Gets a value indicating whether the Type can be hosted in a context. |
IsEnum | Read-only Gets a value indicating whether the current Type represents an enumeration. |
IsExplicitLayout | Read-only Gets a value indicating whether the class layout attribute ExplicitLayout is selected for the Type. |
IsImport | Read-only Gets a value indicating whether the Type was imported from another class. |
IsInterface | Read-only Gets a value indicating whether the Type is an interface; that is, not a class or a value type. |
IsLayoutSequential | Read-only Gets a value indicating whether the class layout attribute SequentialLayout is selected for the Type. |
IsMarshalByRef | Read-only Gets a value indicating whether the Type is marshaled by reference. |
IsNestedAssembly | Read-only Gets a value indicating whether the Type is nested and visible only within its own assembly. |
IsNestedFamANDAssem | Read-only 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 | Read-only Gets a value indicating whether the Type is nested and visible only within its own family. |
IsNestedFamORAssem | Read-only 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 | Read-only Gets a value indicating whether the Type is nested and declared private. |
IsNestedPublic | Read-only Gets a value indicating whether a class is nested and declared public. |
IsNotPublic | Read-only Gets a value indicating whether the top-level Type is not declared public. |
IsPointer | Read-only Gets a value indicating whether the Type is a pointer. |
IsPrimitive | Read-only Gets a value indicating whether the Type is one of the primitive types. |
IsPublic | Read-only Gets a value indicating whether the top-level Type is declared public. |
IsSealed | Read-only Gets a value indicating whether the Type is declared sealed. |
IsSerializable | Read-only Gets a value indicating whether the Type is serializable. |
IsSpecialName | Read-only Gets a value indicating whether the Type has a name that requires special handling. |
IsUnicodeClass | Read-only Gets a value indicating whether the string format attribute UnicodeClass is selected for the Type. |
IsValueType | Read-only Gets a value indicating whether the Type is a value type. |
MemberType | Read-only Overridden: Gets a bitmask indicating the member type. |
Module | Read-only Gets the module (the DLL) in which the current Type is defined. |
Name (inherited from System.Reflection.MemberInfo) |
Read-only See base class member description: System.Reflection.MemberInfo.Name Gets the name of this member. |
Namespace | Read-only Gets the namespace of the Type. |
ReflectedType | Read-only Overridden: Gets the class object that was used to obtain this member. |
TypeHandle | Read-only Gets the handle for the current Type. |
TypeInitializer | Read-only Gets the initializer for the Type. |
UnderlyingSystemType | Read-only Indicates the type provided by the common language runtime that represents this type. |
Equals | Overloaded:Equals(object o) Overridden: Determines if the underlying system type of the current Type is the same as the underlying system type of the specified Object. |
Equals | Overloaded:Equals(Type o) Determines if the underlying system type of the current Type is the same as the underlying system type of the specified Type. |
FindInterfaces | Returns an array of Type objects representing a filtered list of interfaces implemented or inherited by the current Type. |
FindMembers | Returns a filtered array of MemberInfo objects of the specified member type. |
GetArrayRank | Gets the number of dimensions in an Array. |
GetConstructor | Overloaded:GetConstructor(Type[] types) Searches for a public instance constructor whose parameters match the types in the specified array. |
GetConstructor | Overloaded:GetConstructor(BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers) Searches for a constructor whose parameters match the specified argument types and modifiers, using the specified binding constraints. |
GetConstructor | Overloaded:GetConstructor(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) Searches for a constructor whose parameters match the specified argument types and modifiers, using the specified binding constraints and the specified calling convention. |
GetConstructors | Overloaded:GetConstructors() Returns all the public constructors defined for the current Type. |
GetConstructors | Overloaded:GetConstructors(BindingFlags bindingAttr) When overridden in a derived class, searches for the constructors defined for the current Type, using the specified BindingFlags. |
GetCustomAttributes (inherited from System.Reflection.MemberInfo) |
Overloaded:GetCustomAttributes(bool inherit) See base class member description: System.Reflection.MemberInfo.GetCustomAttributesWhen overridden in a derived class, returns an array of all of the custom attributes. |
GetCustomAttributes (inherited from System.Reflection.MemberInfo) |
Overloaded:GetCustomAttributes(Type attributeType, bool inherit) See base class member description: System.Reflection.MemberInfo.GetCustomAttributesWhen overridden in a derived class, returns an array of custom attributes identified by Type. |
GetDefaultMembers | Searches for the members defined for the current Type whose DefaultMemberAttribute is set. |
GetElementType | When overridden in a derived class, returns the Type of the object encompassed or referred to by the current array, pointer or reference type. |
GetEvent | Overloaded:GetEvent(string name) Returns the EventInfo object representing the specified event. |
GetEvent | Overloaded:GetEvent(string name, BindingFlags bindingAttr) When overridden in a derived class, returns the EventInfo object representing the specified event, using the specified binding constraints. |
GetEvents | Overloaded:GetEvents() Returns all the public events that are declared or inherited by the current Type. |
GetEvents | Overloaded:GetEvents(BindingFlags bindingAttr) When overridden in a derived class, searches for events that are declared or inherited by the current Type, using the specified binding constraints. |
GetField | Overloaded:GetField(string name) Searches for the field with the specified name. |
GetField | Overloaded:GetField(string name, BindingFlags bindingAttr) Searches for the specified field, using the specified binding constraints. |
GetFields | Overloaded:GetFields() Returns all the public fields of the current Type. |
GetFields | Overloaded:GetFields(BindingFlags bindingAttr) When overridden in a derived class, searches for the fields defined for the current Type, using the specified binding constraints. |
GetHashCode | Overridden: Returns the hash code for this instance. |
GetInterface | Overloaded:GetInterface(string name) Searches for the interface with the specified name. |
GetInterface | Overloaded:GetInterface(string name, bool ignoreCase) When overridden in a derived class, searches for the specified interface, specifying whether to do a case-sensitive search. |
GetInterfaceMap | Returns an interface mapping for the specified interface type. |
GetInterfaces | When overridden in a derived class, gets all the interfaces implemented or inherited by the current Type. |
GetMember | Overloaded:GetMember(string name) Searches for the members with the specified name. |
GetMember | Overloaded:GetMember(string name, BindingFlags bindingAttr) Searches for the specified members, using the specified binding constraints. |
GetMember | Overloaded:GetMember(string name, MemberTypes type, BindingFlags bindingAttr) Searches for the specified members of the specified member type, using the specified binding constraints. |
GetMembers | Overloaded:GetMembers() Returns all the public members of the current Type. |
GetMembers | Overloaded:GetMembers(BindingFlags bindingAttr) When overridden in a derived class, searches for the members defined for the current Type, using the specified binding constraints. |
GetMethod | Overloaded:GetMethod(string name) Searches for the public method with the specified name. |
GetMethod | Overloaded:GetMethod(string name, BindingFlags bindingAttr) Searches for the specified method, using the specified binding constraints. |
GetMethod | Overloaded:GetMethod(string name, Type[] types) Searches for the specified public method whose parameters match the specified argument types. |
GetMethod | Overloaded:GetMethod(string name, Type[] types, ParameterModifier[] modifiers) Searches for the specified public method whose parameters match the specified argument types and modifiers. |
GetMethod | Overloaded:GetMethod(string name, BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers) Searches for the specified method whose parameters match the specified argument types and modifiers, using the specified binding constraints. |
GetMethod | Overloaded:GetMethod(string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) Searches for the specified method whose parameters match the specified argument types and modifiers, using the specified binding constraints and the specified calling convention. |
GetMethods | Overloaded:GetMethods() Returns all the public methods of the current Type. |
GetMethods | Overloaded:GetMethods(BindingFlags bindingAttr) When overridden in a derived class, searches for the methods defined for the current Type, using the specified binding constraints. |
GetNestedType | Overloaded:GetNestedType(string name) Searches for the nested type with the specified name. |
GetNestedType | Overloaded:GetNestedType(string name, BindingFlags bindingAttr) When overridden in a derived class, searches for the specified nested type, using the specified binding constraints. |
GetNestedTypes | Overloaded:GetNestedTypes() Returns all the types nested within the current Type. |
GetNestedTypes | Overloaded:GetNestedTypes(BindingFlags bindingAttr) When overridden in a derived class, searches for the types nested within the current Type, using the specified binding constraints. |
GetProperties | Overloaded:GetProperties() Returns all the public properties of the current Type. |
GetProperties | Overloaded:GetProperties(BindingFlags bindingAttr) When overridden in a derived class, searches for the properties of the current Type, using the specified binding constraints. |
GetProperty | Overloaded:GetProperty(string name) Searches for the public property with the specified name. |
GetProperty | Overloaded:GetProperty(string name, BindingFlags bindingAttr) Searches for the specified property, using the specified binding constraints. |
GetProperty | Overloaded:GetProperty(string name, Type returnType) Searches for the public property with the specified name and return type. |
GetProperty | Overloaded:GetProperty(string name, Type[] types) Searches for the specified public property whose parameters match the specified argument types. |
GetProperty | Overloaded:GetProperty(string name, Type returnType, Type[] types) Searches for the specified public property whose parameters match the specified argument types. |
GetProperty | Overloaded:GetProperty(string name, Type returnType, Type[] types, ParameterModifier[] modifiers) Searches for the specified public property whose parameters match the specified argument types and modifiers. |
GetProperty | Overloaded:GetProperty(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) Searches for the specified property whose parameters match the specified argument types and modifiers, using the specified binding constraints. |
GetType (inherited from System.Object) |
Overloaded:GetType() See base class member description: System.Object.GetTypeDerived from System.Object, the primary base class for all objects. |
GetType | Overloaded:GetType(string typeName) Gets the Type with the specified name, performing a case-sensitive search. |
GetType | Overloaded:GetType(string typeName, bool throwOnError) Gets the Type with the specified name, performing a case-sensitive search and specifying whether to throw an exception if an error occurs while loading the Type. |
GetType | Overloaded:GetType(string typeName, bool throwOnError, bool ignoreCase) Gets the Type with the specified name, specifying whether to perform a case-sensitive search and whether to throw an exception if an error occurs while loading the Type. |
GetTypeArray | Gets the types of the objects in the specified array. |
GetTypeCode | Gets the underlying type code of the specified Type. |
GetTypeFromHandle | Gets the Type referenced by the specified type handle. |
GetTypeHandle | Gets the handle for the Type of a specified object. |
InvokeMember | Overloaded:InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args) Invokes the specified member, using the specified binding constraints and matching the specified argument list. |
InvokeMember | Overloaded:InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, CultureInfo culture) Invokes 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) When overridden in a derived class, invokes the specified member, using the specified binding constraints and matching the specified argument list, modifiers and culture. |
IsAssignableFrom | Determines whether an instance of the current Type can be assigned from an instance of the specified Type. |
IsDefined (inherited from System.Reflection.MemberInfo) |
See base class member description: System.Reflection.MemberInfo.IsDefined When overridden in a derived class, indicates whether one or more instance of attributeType is defined on this member. |
IsInstanceOfType | Determines whether the specified object is an instance of the current Type. |
IsSubclassOf | Determines whether the current Type derives from the specified Type. |
ToString | Overridden: Returns a String representing the name of the current Type. |
ctor #1 | Default constructor. This constructor is called by derived class constructors to initialize state in this type. Initializes a new instance of the Type class. |
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 | When overridden in a derived class, implements the Type.Attributes property and gets a bitmask indicating the attributes associated with the Type. |
GetConstructorImpl | When overridden in a derived class, searches for a constructor whose parameters match the specified argument types and modifiers, using the specified binding constraints and the specified calling convention. |
GetMethodImpl | When overridden in a derived class, 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 | When overridden in a derived class, searches for the specified property whose parameters match the specified argument types and modifiers, using the specified binding constraints. |
HasElementTypeImpl | When overridden in a derived class, implements the Type.HasElementType property and determines 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. |
IsArrayImpl | When overridden in a derived class, implements the Type.IsArray property and determines whether the Type is an array. |
IsByRefImpl | When overridden in a derived class, implements the Type.IsByRef property and determines whether the Type is passed by reference. |
IsCOMObjectImpl | When overridden in a derived class, implements the Type.IsCOMObject property and determines whether the Type is a COM object. |
IsContextfulImpl | Implements the Type.IsContextful property and determines whether the Type can be hosted in a context. |
IsMarshalByRefImpl | Implements the Type.IsMarshalByRef property and determines whether the Type is marshalled by reference. |
IsPointerImpl | When overridden in a derived class, implements the Type.IsPointer property and determines whether the Type is a pointer. |
IsPrimitiveImpl | When overridden in a derived class, implements the Type.IsPrimitive property and determines whether the Type is one of the primitive types. |
IsValueTypeImpl | Implements the Type.IsValueType property and determines whether the Type is a value type; that is, not a class or an interface. |
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:
protected Type(); |
public static readonly char Delimiter;
|
typeNameSpace + Type.Delimiter + baseName + '.' + cultureName [+ '-' + subCultureName] + '.resources'
public static readonly Type[] EmptyTypes;
|
cInfo = type.GetConstructor (BindingFlags.ExactBinding, null, Type.EmptyTypes, null);
public static readonly MemberFilter FilterAttribute;
|
For example, the Object can be assigned the value of a field from FieldAttributes such as Public. In that case, when the FilterAttribute delegate is invoked, it will return true only if the method represented by the MemberInfo object is decorated with the public field attribute in metadata.
using System; using System.Reflection; using System.Security; public class MyFilterAttributeSample { public static void Main() { try { MemberFilter myFilter = Type.FilterAttribute; Type myType = typeof(System.String); MemberInfo[] myMemberInfoArray = myType.FindMembers(MemberTypes.Constructor |MemberTypes.Method, BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance, myFilter, MethodAttributes.SpecialName); foreach (MemberInfo myMemberinfo in myMemberInfoArray) { Console.Write ("\n" + myMemberinfo.Name); Console.Write (" is a " + myMemberinfo.MemberType.ToString()); } } catch(ArgumentNullException e) { Console.Write("ArgumentNullException : " + e.Message); } catch(SecurityException e) { Console.Write("SecurityException : " + e.Message); } catch(Exception e) { Console.Write("Exception :" + e.Message); } } }
public static readonly MemberFilter FilterName;
|
For example, the Object may be assigned the value "Byte*". In that case, when the FilterName delegate is invoked, it will return true only if the method represented by the MemberInfo object has a name that begins with "Byte".
// Get the set of methods associated with the type MemberInfo[] mi = typeof(Application).FindMembers(MemberTypes.Constructor | MemberTypes.Method, BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly, Type.FilterName, "*"); Console.WriteLine("Number of methods (includes constructors): " + mi.Length);
public static readonly MemberFilter FilterNameIgnoreCase;
|
For example, the Object may be assigned the value "ByTe*". In that case, when the FilterName delegate is invoked, it will return true only if the method represented by the MemberInfo object has a name that begins with "byte", ignoring case.
using System; using System.Reflection; using System.Security; public class MyFilterNameIgnoreCaseSample { public static void Main() { try { MemberFilter myFilter = Type.FilterNameIgnoreCase; Type myType = typeof(System.String); MemberInfo[] myMemberinfo1 = myType.FindMembers(MemberTypes.Constructor |MemberTypes.Method, BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance, myFilter, "C*"); foreach (MemberInfo myMemberinfo2 in myMemberinfo1) { Console.Write("\n" + myMemberinfo2.Name); MemberTypes Mymembertypes = myMemberinfo2.MemberType; Console.WriteLine(" is a " + Mymembertypes.ToString()); } } catch(ArgumentNullException e) { Console.Write("ArgumentNullException : " + e.Message); } catch(SecurityException e) { Console.Write("SecurityException : " + e.Message); } catch(Exception e) { Console.Write("Exception : " + e.Message); } } }
public static readonly object Missing;
|
This code produces the following output:
a = 10 b = 55.3 c = 12
a = 10 b = 1.3 c = 1
a = 10 b = 1.2 c = 1
public abstract Assembly Assembly {get;}
|
using System; using System.Reflection; class MyAssemblyClass { public static void Main() { Type objType = typeof(System.Array); // Print the assembly Fullname. Console.WriteLine ("Assembly Fullname -\t" + objType.Assembly.FullName.ToString() + "\n" ); // Print the assembly Qualified Name. Console.WriteLine ("Assembly Qualified name -\t" + objType.AssemblyQualifiedName.ToString()); } }
public abstract string AssemblyQualifiedName {get;}
|
Delimiter | Meaning |
---|---|
Backslash (\) | Escape character. |
Comma (,) | Precedes the Assembly name. |
Plus sign (+) | Precedes a nested class. |
Period (.) | Denotes namespace identifiers. |
For example, the fully qualified name for a class might look like this:
TopNamespace.SubNameSpace.ContainingClass+NestedClass,MyAssembly
If the namespace were TopNamespace.Sub+Namespace, then the string would have to precede the plus sign (+) with an escape character (\) to prevent it from being interpreted as a nesting separator. Reflection emits this string as follows:
TopNamespace.Sub\+Namespace.ContainingClass+NestedClass,MyAssembly
A "++" becomes "\+\+", and a "\" becomes "\\".
This qualified name can be persisted and later used to load the Type. To search for and load a Type, use Type.GetType either with the type name only or with the assembly qualified type name. Type.GetType with the type name only will look for the Type in the caller's assembly and then in the System assembly. Type.GetType with the assembly qualified type name will look for the Type in any assembly.
Type names may include trailing characters that denote additional information about the type, such as whether the type is a reference type, a pointer type or an array type. To retrieve the type name without these trailing characters, use
t.GetElementType().ToString()
, where t is the type.
Spaces are relevant in all type name components except the assembly name. In the assembly name, spaces before the ',' separator are relevant, but spaces after the ',' separator are ignored.
using System; using System.Reflection; class MyAssemblyClass { public static void Main() { Type objType = typeof(System.Array); // Print the assembly Fullname. Console.WriteLine ("Assembly Fullname -\t" + objType.Assembly.FullName.ToString() + "\n" ); // Print the assembly Qualified Name. Console.WriteLine ("Assembly Qualified name -\t" + objType.AssemblyQualifiedName.ToString()); } }
public TypeAttributes Attributes {get;}
|
public abstract Type BaseType {get;}
|
Interfaces inherit from Object and from zero or more base interfaces; therefore, the base type of an interface is considered to be Object. The base interfaces can be determined with Type.GetInterfaces or Type.FindInterfaces.
This property is read-only.
using System; class TestType { public static void Main() { Type t = typeof(int); Console.WriteLine("{0} inherits from {1}", t,t.BaseType); } }
This code produces the following output:
System.Int32 inherits from System.ValueType
public override Type DeclaringType {get;}
|
using System; using System.Reflection; public abstract class dtype { public abstract class MyClassA { public abstract int m(); } public abstract class MyClassB : MyClassA { } public static void Main(string[] args) { Console.WriteLine("Declaring type of m is {0}", typeof(MyClassB).GetMethod("m").DeclaringType); } }
This code produces the following output:
Declaring type of m is dtype+MyClassA
public static Binder DefaultBinder {get;}
|
The general principle is that Binder.ChangeType should perform only widening coercions, which never lose data. An example of a widening coercion is coercing a value that is a 32-bit signed integer to a value that is a 64-bit signed integer. This is distinguished from a narrowing coercion, which may lose data. An example of a narrowing coercion is coercing a 64-bit signed integer to a 32-bit signed integer.
The following table lists the coercions performed by the default ChangeType.
Source Type | Target Type |
---|---|
Any type | Its base type. |
Any type | The interface it implements. |
Char | Unt16, UInt32, Int32, UInt64, Int64, Single, Double |
Byte | Char, Unt16, Int16, UInt32, Int32, UInt64, Int64, Single, Double |
SByte | Int16, Int32, Int64, Single, Double |
UInt16 | UInt32, Int32, UInt64, Int64, Single, Double |
Int16 | Int32, Int64, Single, Double |
UInt32 | UInt64, Int64, Single, Double |
Int32 | Int64, Single, Double |
UInt64 | Single, Double |
Int64 | Single, Double |
Single | Double |
Non-reference | By-reference. |
using System; using System.Reflection; public class MyDefaultBinderSample { public static void Main() { try { Binder defaultBinder = Type.DefaultBinder; MyClass myClass = new MyClass(); // Invoke HelloWorld method of Myclass. myClass.GetType().InvokeMember("HelloWorld", BindingFlags.InvokeMethod, defaultBinder, myClass, new object [] {}); } catch(Exception e) { Console.WriteLine("Exception :" + e.Message); } } class MyClass { public void HelloWorld() { Console.WriteLine("Hello World"); } } }
public abstract string FullName {get;}
|
This property is read-only.
using System; class TestFullName { public static void Main() { Type t = typeof(Array); Console.WriteLine("Full name of Array type is {0}",t.FullName); } }
This code produces the following output:
Full name of Array type is
System.Array
public abstract Guid GUID {get;}
|
// Get the type corresponding to the class 'MyClass'. Type myType = typeof(MyClass1); // Get the object of the 'Guid'. Guid myGuid =(Guid) myType.GUID; Console.WriteLine("The Name of the Class is :"+myType.ToString()); Console.WriteLine("The ClassId of the 'MyClass' is :"+myType.GUID);
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 abstract Module Module {get;}
|
public abstract string Name {get;}
|
To get the Name property, get the class Type. From the Type, get the MemberInfo array. From a MemberInfo element of the array, obtain the Name property.
using System; using System.Reflection; class Mymemberinfo { public static int Main() { Console.WriteLine ("\nReflection.MemberInfo"); //Get the Type and MemberInfo. Type MyType = Type.GetType("System.Empty"); MemberInfo[] Mymemberinfoarray = MyType.GetMembers(); //Get and display the DeclaringType method. Console.Write("\nThere are {0} members in ", Mymemberinfoarray.GetLength(0)); Console.Write("{0}.", MyType.FullName); foreach (MemberInfo Mymemberinfo in Mymemberinfoarray) { Console.Write("\n" + Mymemberinfo.Name + " declaring type - " + Mymemberinfo.DeclaringType); } return 0; } } /* This code produces the following output: Reflection.MemberInfo There are 6 members in System.Empty. Value declaring type - System.Empty GetObjectData declaring type - System.Empty GetHashCode declaring type - System.Object Equals declaring type - System.Object ToString declaring type - System.Empty GetType declaring type - System.Object */
public abstract string Namespace {get;}
|
public override Type ReflectedType {get;}
|
using System; using System.Reflection; public abstract class rtype { public abstract class MyClassA { public abstract int m(); } public abstract class MyClassB : MyClassA { } public static void Main(string[] args) { Console.WriteLine("Reflected type of m is {0}", typeof(MyClassB).GetMethod("m").ReflectedType); } }
This code produces the following output:
Reflected type of m is rtype+MyClassB
public abstract RuntimeTypeHandle TypeHandle {get;}
|
class MyClass { public int myField = 10; } class Type_TypeHandle { public static void Main() { try { MyClass myClass = new MyClass(); // Get the Type of 'MyClass'. Type myClassType = myClass.GetType(); // Get the runtimehandle of 'MyClass'. RuntimeTypeHandle myClassHandle = myClassType.TypeHandle; DisplayTypeHandle(myClassHandle); } catch(Exception e) { Console.WriteLine("Exception : {0} " , e.Message ); } } public static void DisplayTypeHandle(RuntimeTypeHandle myTypeHandle) { // Get the type from the handle. Type myType = Type.GetTypeFromHandle(myTypeHandle); // Display the type. Console.WriteLine("\nDisplaying the type from the handle.\n"); Console.WriteLine("The type is : '{0}' ", myType.ToString()); } }
public ConstructorInfo TypeInitializer {get;}
|
public abstract Type UnderlyingSystemType {get;}
|
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
~Type(); |
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 abstract 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 abstract ConstructorInfo GetConstructorImpl( |
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 are used for 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.
This method implements Type.GetConstructor.
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.GetConstructor and Type.GetConstructorImpl cannot be used to obtain a class initializer. Class initializers are available only through Type.GetMember, Type.GetMembers, Type.FindMembers, and Type.GetConstructors.
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 abstract ConstructorInfo[] GetConstructors( |
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.
-or-
An empty array of type ConstructorInfo, if no constructors are defined for the current Type, or if none of the defined constructors match the binding constraints.
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.
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.
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
inherit
using System; using System.Reflection; // Define a custom attribute with one named parameter. [AttributeUsage(AttributeTargets.All)] public class MyAttribute : Attribute { private string myName; public MyAttribute(string name) { myName = name; } public string Name { get { return myName; } } } // Define a class which has the custom attribute associated with one of its members. public class MyClass1 { [MyAttribute("This is an example attribute")] public void MyMethod(int i) { return; } } public class MemberInfo_GetCustomAttributes { public static void Main() { try { // Get the type of the class 'MyClass1'. Type myType = typeof(MyClass1); // Get the members associated with the class 'MyClass1'. MemberInfo[] myMembers = myType.GetMembers(); // Display the attributes for each of the members of the class 'MyClass1'. for(int i = 0; i < myMembers.Length; i++) { Object[] myAttributes = myMembers[i].GetCustomAttributes(false); if(myAttributes.Length > 0) { Console.WriteLine("\nThe attributes for the member {0} are : \n", myMembers[i]); for(int j = 0; j < myAttributes.Length; j++) Console.WriteLine("The type of the attribute is : {0}", myAttributes[j]); } } } catch(Exception e) { Console.WriteLine("Exception Caught! "+e.Message); } } }
attributeType
inherit
Exception Type | Condition |
---|---|
TypeLoadException | If the custom attribute type can not be loaded. |
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 abstract Type GetElementType(); |
-or-
null if the current Type is not an array or a pointer, or is not passed by reference.
using System; class TestGetElementType { public static void Main() { int[] array = {1,2,3}; Type t = array.GetType(); Type t2 = t.GetElementType(); Console.WriteLine("{0} element type is {1}",array, t2.ToString()); TestGetElementType newMe = new TestGetElementType(); t = newMe.GetType(); t2 = t.GetElementType(); Console.WriteLine("{0} element type is {1}", newMe, t2==null? "null" : t2.ToString()); } }
This code produces the following output:
System.Int32[] element type is System.Int32 TestGetElementType element type is null
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 abstract EventInfo GetEvent( |
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. |
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.
// Creates a bitmask comprising BindingFlags. BindingFlags myBindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; Type myTypeBindingFlags = typeof(System.Windows.Forms.Button); EventInfo myEventBindingFlags = myTypeBindingFlags.GetEvent("Click", myBindingFlags); if(myEventBindingFlags != null) { Console.WriteLine("Looking for Click event in Button class with specified BindingFlags."); Console.WriteLine(myEventBindingFlags.ToString()); } else Console.WriteLine("The Click event is not available with Button class");
public virtual EventInfo[] GetEvents(); |
-or-
An empty array of type EventInfo, if the current Type does not have public events.
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[] myEvents = myType.GetEvents(); Console.WriteLine("The events on Button class are : "); for (int index = 0; index < myEvents.Length; index++) { Console.WriteLine(myEvents[index].ToString()); }
public abstract EventInfo[] GetEvents( |
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.
-or-
An empty array of type EventInfo, if the current Type does not have events, or if none of the events match the binding constraints.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.
// Creates a bitmask comprising BindingFlags. BindingFlags myBindingFlags = BindingFlags.Instance | BindingFlags.Public; Type myTypeEvent = typeof(System.Windows.Forms.Button); EventInfo[] myEventsBindingFlags = myTypeEvent.GetEvents(myBindingFlags); Console.WriteLine("\nThe events on Button class with specified BindingFlags are : "); for (int index = 0; index < myEventsBindingFlags.Length; index++) { Console.WriteLine(myEventsBindingFlags[index].ToString()); }
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 abstract FieldInfo GetField( |
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. |
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 following BindingFlags filter flags can be used to define which fields 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 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 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 abstract FieldInfo[] GetFields( |
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.
-or-
An empty array of type FieldInfo, if no fields are defined for the current Type, or if none of the defined fields match the binding constraints.
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.
Console.WriteLine("HashCode of the System.Windows.Forms.Button type is : {0}", typeof(System.Windows.Forms.Button).GetHashCode());
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
-or-
false to perform a case-sensitive search for name.
true to perform a case-insensitive search for name.-or-
false to perform a case-sensitive search for 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()); } }
public virtual InterfaceMapping GetInterfaceMap( |
interfaceType
Exception Type | Condition |
---|---|
ArgumentException | The interfaceType parameter does not refer to an interface. |
ArgumentNullException | interfaceType is null. |
public abstract Type[] GetInterfaces(); |
-or-
An empty array of type Type, if no interfaces are implemented or inherited by the current Type.
Exception Type | Condition |
---|---|
TargetInvocationException | A static initializer is invoked and throws an exception. |
public class MyTemplate : Control, INamingContainer { private String _message = null; public String Message { get { return _message; } set { _message = value; } } } public class MyInterfacesSample { public static void Main() { try { Type[] myObjectArray= typeof(MyTemplate).GetInterfaces(); Console.WriteLine("The Interfaces inherited by the MyTemplate class are :\n"); for (int index = 0; index < myObjectArray.Length; index++) { Console.WriteLine(myObjectArray[index]); } } catch (Exception e) { Console.WriteLine("Exception Raised !"); Console.WriteLine("Message : " + e.Message); } } }
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 virtual MemberInfo[] GetMember( |
name
type
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. |
NotSupportedException | A derived class must provide an implementation. |
This method searches the current classes and its base classes. 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.
Class initializers are available through Type.GetMember, Type.GetMembers, Type.FindMembers, and Type.GetConstructors.
public void GetPublicInstanceMethodMemberInfo() { String myString = "GetMember_String_MemberType_BindingFlag"; Type myType = myString.GetType(); // Get the Public Instance methods for myString starting with 'C'. MemberInfo[] myMembers = myType.GetMember("C*", MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance); if(myMembers.Length > 0) { Console.WriteLine("\nThe Public Instance Method(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 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 abstract MemberInfo[] GetMembers( |
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.
-or-
An empty array of type MemberInfo, if no members are defined for the current Type, or if none of the defined members match the binding constraints.
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:
Calling this method with only the Public flag or only the NonPublic flag will return the specified members and does not require any other flags.
See BindingFlags for more information.
Class initializers are available through Type.GetMember, Type.GetMembers, Type.FindMembers, and Type.GetConstructors.
class MyClass { public int myInt = 0; public string myString = null; public MyClass() { } public void Myfunction() { } } class Type_GetMembers_BindingFlags { public static void Main() { try { MyClass MyObject = new MyClass(); MemberInfo [] myMemberInfo; // Get the type of the class 'MyClass'. Type myType = MyObject.GetType(); // Get the public instance members of the class 'MyClass'. myMemberInfo = myType.GetMembers(BindingFlags.Public|BindingFlags.Instance); Console.WriteLine( "\nThe public instance members of class '{0}' are : \n", myType); for (int i =0 ; i < myMemberInfo.Length ; i++) { // Display name and type of the member of 'MyClass'. Console.WriteLine( "'{0}' is a {1}", myMemberInfo[i].Name, myMemberInfo[i].MemberType); } } catch (SecurityException e) { Console.WriteLine("SecurityException : " + e.Message ); } } }
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 abstract MethodInfo GetMethodImpl( |
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.
-or-
null. If types is null, arguments are not matched.
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.
-or-
null. If types is null, arguments are not matched.
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. |
ArgumentException | types is multidimensional. -or- modifiers is multidimensional. -or- types and modifiers do not have the same length. |
If types is null, arguments are not matched.
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 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 abstract MethodInfo[] GetMethods( |
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.
-or-
An empty array of type MethodInfo, if no methods are defined for the current Type, or if none of the defined methods match the binding constraints.
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 static void Main() { Type myType =(typeof(MyTypeClass)); // Get the methods with the Access-Specifier as public. MethodInfo[] myArrayMethodInfo = myType.GetMethods(BindingFlags.Public|BindingFlags.Instance|BindingFlags.DeclaredOnly); Console.WriteLine("\nThe Number of Public Methods are :"+myArrayMethodInfo.Length); Console.WriteLine("The Names of the Public Methods are :"); // Display all the methods. DisplayMethodInfo(myArrayMethodInfo); // Get the methods information of all 'NonPublic'. MethodInfo[] myArrayMethodInfo1 = myType.GetMethods(BindingFlags.NonPublic|BindingFlags.Instance|BindingFlags.DeclaredOnly); Console.WriteLine("\nThe Number of Protected Methods are :"+myArrayMethodInfo1.Length); Console.WriteLine("The Names of the Protected methods are :"); // Display all the methods information. DisplayMethodInfo(myArrayMethodInfo1); } public static void DisplayMethodInfo(MethodInfo[] myArrayMethodInfo) { // Display the information of all the Methods. for(int i=0;i<myArrayMethodInfo.Length;i++) { MethodInfo myMethodInfo = (MethodInfo)myArrayMethodInfo[i]; Console.WriteLine("\nName of the Method is :"+myMethodInfo.Name); } }
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 abstract Type GetNestedType( |
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. |
The following BindingFlags modifier flags can be used to change how the search works:
See BindingFlags for more information.
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 abstract Type[] GetNestedTypes( |
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.
-or-
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.
The following BindingFlags modifier flags can be used to change how the search works:
Calling this method with only the Public flag or only the NonPublic flag will return the specified nested types and does not require any other flags.
See BindingFlags for more information.
public static void Main() { Type myType =(typeof(MyTypeClass)); // Get the Nested classes with the Access-Specifier as public. Type[] myTypeArray = myType.GetNestedTypes(BindingFlags.Public|BindingFlags.Instance); Console.WriteLine("\nThe Public Classes are :"+myTypeArray.Length); Console.WriteLine("\nThe Names of the Public Classes are :"); // Display all the Nested classes. DisplayTypeInfo(myTypeArray); // Get the Nested classes information of all 'NonPublic'. Type[] myTypeArray1 = myType.GetNestedTypes(BindingFlags.NonPublic|BindingFlags.Instance); Console.WriteLine("\nThe Number of Protected Classes are :"+myTypeArray1.Length); Console.WriteLine("\nThe Names of the Protected Classes are :"); // Display the information of all the Nested classes. DisplayTypeInfo(myTypeArray1); } public static void DisplayTypeInfo(Type[] myArrayType) { // Display the information of all the Nested classes. for(int i=0;i<myArrayType.Length;i++) { Type myType = (Type)myArrayType[i]; Console.WriteLine("\nName of the Nested class is :"+myType.ToString()); } }
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 abstract PropertyInfo[] GetProperties( |
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.
-or-
An empty array of type PropertyInfo, if the current Type does not have properties, or if none of the properties match the binding constraints.
Otherwise, the property is private and you must use type.GetProperty("propertyname", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static) to get it.
The following BindingFlags filter flags can be used to define which nested types 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 static void Main() { Type myType =(typeof(MyTypeClass)); // Get the properties having the Access-Specifier as public. PropertyInfo[] myPropertyInfo = myType.GetProperties(BindingFlags.Public|BindingFlags.Instance); Console.WriteLine("\nThe Number of Public Properties are :"+myPropertyInfo.Length); Console.WriteLine("\nThe Names of the Public properties are :"); // Display all the properties. DisplayPropertyInfo(myPropertyInfo); // Get the properties information of all 'NonPublic'. PropertyInfo[] myPropertyInfo1 = myType.GetProperties(BindingFlags.NonPublic|BindingFlags.Instance); Console.WriteLine("\nThe Number of Protected Properties are :"+myPropertyInfo1.Length); Console.WriteLine("\nThe Names of the Protected properties are :"); // Display all the properties information. DisplayPropertyInfo(myPropertyInfo1); } public static void DisplayPropertyInfo(PropertyInfo[] myPropertyInfo) { // Display the information of all the properties . for(int i=0;i<myPropertyInfo.Length;i++) { PropertyInfo myPropInfo = (PropertyInfo)myPropertyInfo[i]; Console.WriteLine("\nName of the property is :"+myPropInfo.Name); Console.WriteLine("Type of the property is :"+myPropInfo.PropertyType); } }
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 abstract PropertyInfo GetPropertyImpl( |
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 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 |
---|---|
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 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 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.
public Type GetType(); |
typeName
Exception Type | Condition |
---|---|
ArgumentNullException | typeName is null. |
TargetInvocationException | A class initializer is invoked and throws an exception. |
To use GetType on a dynamic module, subscribe to the AppDomain.AssemblyResolve event and call GetType before saving. Otherwise, you will get two copies of the assembly in memory.
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. |
Arrays or COM types are not searched for unless they have already been loaded into the table of available classes.
typeName can be a simple type name, a type name that includes a namespace, or a complex name that includes an assembly name specification.
If typeName includes only the name of the Type, this method searches in the calling object's assembly, then in the mscorlib.dll assembly. If typeName is fully qualified with the partial or complete assembly name, this method searches in the specified assembly.
Type.AssemblyQualifiedName can return a fully qualified type name including nested types and the assembly name. All compilers that support the common language runtime will emit the simple name of a nested class, and reflection constructs a mangled name when queried, in accordance with the following conventions.
Delimiter | Meaning |
---|---|
Backslash (\) | Escape character. |
Comma (,) | Precedes the Assembly name. |
Plus sign (+) | Precedes a nested class. |
Period (.) | Denotes namespace identifiers. |
For example, the fully qualified name for a class might look like this:
TopNamespace.SubNameSpace.ContainingClass+NestedClass,MyAssembly
If the namespace were TopNamespace.Sub+Namespace, then the string would have to precede the plus sign (+) with an escape character (\) to prevent it from being interpreted as a nesting separator. Reflection emits this string as follows:
TopNamespace.Sub\+Namespace.ContainingClass+NestedClass,MyAssembly
A "++" becomes "\+\+", and a "\" becomes "\\".
This qualified name can be persisted and later used to load the Type. To search for and load a Type, use Type.GetType either with the type name only or with the assembly qualified type name. Type.GetType with the type name only will look for the Type in the caller's assembly and then in the System assembly. Type.GetType with the assembly qualified type name will look for the Type in any assembly.
Type names may include trailing characters that denote additional information about the type, such as whether the type is a reference type, a pointer type or an array type. To retrieve the type name without these trailing characters, use
t.GetElementType().ToString()
, where t is the type.
Spaces are relevant in all type name components except the assembly name. In the assembly name, spaces before the ',' separator are relevant, but spaces after the ',' separator are ignored.
The following table shows the syntax you use with GetType for various types.
To Get | Use |
---|---|
An unmanaged pointer to MyType | Type.GetType("MyType*") |
An unmanaged pointer to a pointer to MyType | Type.GetType("MyType**") |
A managed pointer or reference to MyType | Type.GetType("MyType&") . Note that unlike pointers, references are limited to one level. |
A parent class and a nested class | Type.GetType("MyParentClass+MyNestedClass") |
A one-dimensional array with a lower bound of 0 | Type.GetType("MyArray[]") |
A one-dimensional array with an unknown lower bound | Type.GetType("MyArray[*]") |
An n-dimensional array | A comma (,) inside the brackets a total of n-1 times. For example, System.Object[,,] represents a three-dimensional Object array. |
A two-dimensional array's array | Type.GetType("MyArray[][]") |
A rectangular two-dimensional array with unknown lower bounds | Type.GetType("MyArray[*,*]") or Type.GetType("MyArray[,]") |
try { // Create object of 'Type' class. Type myType1 = Type.GetType("System.Int32"); Console.WriteLine("The 'Fullname' is {0} ", myType1.FullName); // Since 'NoAssembly' assembly does not exist, 'GetType' throws 'TypeLoadException'. Type myType2 = Type.GetType("NoAssembly", true); Console.WriteLine("The 'Fullname' is {0} ", myType2.FullName); } catch(TypeLoadException e) { Console.WriteLine(e.Message); }
typeName
throwOnError
Exception Type | Condition |
---|---|
ArgumentNullException | typeName is null. |
TargetInvocationException | A class initializer is invoked and throws an exception. |
TypeLoadException | throwOnError is true and an error is encountered while loading the Type. |
To use GetType on a dynamic module, subscribe to the AppDomain.AssemblyResolve event and call GetType before saving. Otherwise, you will get two copies of the assembly in memory.
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. |
Arrays or COM types are not searched for unless they have already been loaded into the table of available classes.
typeName can be a simple type name, a type name that includes a namespace, or a complex name that includes an assembly name specification.
If typeName includes only the name of the Type, this method searches in the calling object's assembly, then in the mscorlib.dll assembly. If typeName is fully qualified with the partial or complete assembly name, this method searches in the specified assembly.
Type.AssemblyQualifiedName can return a fully qualified type name including nested types and the assembly name. All compilers that support the common language runtime will emit the simple name of a nested class, and reflection constructs a mangled name when queried, in accordance with the following conventions.
Delimiter | Meaning |
---|---|
Backslash (\) | Escape character. |
Comma (,) | Precedes the Assembly name. |
Plus sign (+) | Precedes a nested class. |
Period (.) | Denotes namespace identifiers. |
For example, the fully qualified name for a class might look like this:
TopNamespace.SubNameSpace.ContainingClass+NestedClass,MyAssembly
If the namespace were TopNamespace.Sub+Namespace, then the string would have to precede the plus sign (+) with an escape character (\) to prevent it from being interpreted as a nesting separator. Reflection emits this string as follows:
TopNamespace.Sub\+Namespace.ContainingClass+NestedClass,MyAssembly
A "++" becomes "\+\+", and a "\" becomes "\\".
This qualified name can be persisted and later used to load the Type. To search for and load a Type, use Type.GetType either with the type name only or with the assembly qualified type name. Type.GetType with the type name only will look for the Type in the caller's assembly and then in the System assembly. Type.GetType with the assembly qualified type name will look for the Type in any assembly.
Type names may include trailing characters that denote additional information about the type, such as whether the type is a reference type, a pointer type or an array type. To retrieve the type name without these trailing characters, use
t.GetElementType().ToString()
, where t is the type.
Spaces are relevant in all type name components except the assembly name. In the assembly name, spaces before the ',' separator are relevant, but spaces after the ',' separator are ignored.
The following table shows the syntax you use with GetType for various types.
To Get | Use |
---|---|
An unmanaged pointer to MyType | Type.GetType("MyType*") |
An unmanaged pointer to a pointer to MyType | Type.GetType("MyType**") |
A managed pointer or reference to MyType | Type.GetType("MyType&") . Note that unlike pointers, references are limited to one level. |
A parent class and a nested class | Type.GetType("MyParentClass+MyNestedClass") |
A one-dimensional array with a lower bound of 0 | Type.GetType("MyArray[]") |
A one-dimensional array with an unknown lower bound | Type.GetType("MyArray[*]") |
An n-dimensional array | A comma (,) inside the brackets a total of n-1 times. For example, System.Object[,,] represents a three-dimensional Object array. |
A two-dimensional array's array | Type.GetType("MyArray[][]") |
A rectangular two-dimensional array with unknown lower bounds | Type.GetType("MyArray[*,*]") or Type.GetType("MyArray[,]") |
try { // Create object of 'Type' class. Type myType1 = Type.GetType("System.Int32"); Console.WriteLine("The 'Fullname' is {0} ", myType1.FullName); // Since 'NoAssembly' assembly does not exist, 'GetType' throws 'TypeLoadException'. Type myType2 = Type.GetType("NoAssembly", true); Console.WriteLine("The 'Fullname' is {0} ", myType2.FullName); } catch(TypeLoadException e) { Console.WriteLine(e.Message); }
typeName
throwOnError
ignoreCase
-or-
false to perform a case-sensitive search for typeName.
true to perform a case-insensitive search for typeName, if typeName has less than 128 characters.-or-
false to perform a case-sensitive search for typeName.
Exception Type | Condition |
---|---|
ArgumentNullException | typeName is null. |
TargetInvocationException | A class initializer is invoked and throws an exception. |
TypeLoadException | throwOnError is true and an error is encountered while loading the Type. |
To use GetType on a dynamic module, subscribe to the AppDomain.AssemblyResolve event and call GetType before saving. Otherwise, you will get two copies of the assembly in memory.
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. |
Arrays or COM types are not searched for unless they have already been loaded into the table of available classes.
typeName can be a simple type name, a type name that includes a namespace, or a complex name that includes an assembly name specification.
If typeName includes only the name of the Type, this method searches in the calling object's assembly, then in the mscorlib.dll assembly. If typeName is fully qualified with the partial or complete assembly name, this method searches in the specified assembly.
Type.AssemblyQualifiedName can return a fully qualified type name including nested types and the assembly name. All compilers that support the common language runtime will emit the simple name of a nested class, and reflection constructs a mangled name when queried, in accordance with the following conventions.
Delimiter | Meaning |
---|---|
Backslash (\) | Escape character. |
Comma (,) | Precedes the Assembly name. |
Plus sign (+) | Precedes a nested class. |
Period (.) | Denotes namespace identifiers. |
For example, the fully qualified name for a class might look like this:
TopNamespace.SubNameSpace.ContainingClass+NestedClass,MyAssembly
If the namespace were TopNamespace.Sub+Namespace, then the string would have to precede the plus sign (+) with an escape character (\) to prevent it from being interpreted as a nesting separator. Reflection emits this string as follows:
TopNamespace.Sub\+Namespace.ContainingClass+NestedClass,MyAssembly
A "++" becomes "\+\+", and a "\" becomes "\\".
This qualified name can be persisted and later used to load the Type. To search for and load a Type, use Type.GetType either with the type name only or with the assembly qualified type name. Type.GetType with the type name only will look for the Type in the caller's assembly and then in the System assembly. Type.GetType with the assembly qualified type name will look for the Type in any assembly.
Type names may include trailing characters that denote additional information about the type, such as whether the type is a reference type, a pointer type or an array type. To retrieve the type name without these trailing characters, use
t.GetElementType().ToString()
, where t is the type.
Spaces are relevant in all type name components except the assembly name. In the assembly name, spaces before the ',' separator are relevant, but spaces after the ',' separator are ignored.
The following table shows the syntax you use with GetType for various types.
To Get | Use |
---|---|
An unmanaged pointer to MyType | Type.GetType("MyType*") |
An unmanaged pointer to a pointer to MyType | Type.GetType("MyType**") |
A managed pointer or reference to MyType | Type.GetType("MyType&") . Note that unlike pointers, references are limited to one level. |
A parent class and a nested class | Type.GetType("MyParentClass+MyNestedClass") |
A one-dimensional array with a lower bound of 0 | Type.GetType("MyArray[]") |
A one-dimensional array with an unknown lower bound | Type.GetType("MyArray[*]") |
An n-dimensional array | A comma (,) inside the brackets a total of n-1 times. For example, System.Object[,,] represents a three-dimensional Object array. |
A two-dimensional array's array | Type.GetType("MyArray[][]") |
A rectangular two-dimensional array with unknown lower bounds | Type.GetType("MyArray[*,*]") or Type.GetType("MyArray[,]") |
args
Exception Type | Condition |
---|---|
ArgumentNullException | args is null. |
TargetInvocationException | The class initializers are invoked and at least one throws an exception. |
Object[] myObject = new Object[3]; myObject[0] = 66; myObject[1] = "puri"; myObject[2] = 33.33; // Get the array of 'Type' class objects. Type[] myTypeArray = Type.GetTypeArray(myObject); Console.WriteLine("Full names of the 'Type' objects in the array are:"); for(int h = 0; h < myTypeArray.Length ; h++) { Console.WriteLine(myTypeArray[h].FullName); }
type
// Create an object of 'Type' class. Type myType1 = Type.GetType("System.Int32"); // Get the 'TypeCode' of the 'Type' class object created above. TypeCode myTypeCode = Type.GetTypeCode(myType1); Console.WriteLine("TypeCode is: {0}",myTypeCode);
public static Type GetTypeFromHandle( |
handle
Exception Type | Condition |
---|---|
ArgumentNullException | handle is null. |
TargetInvocationException | A class initializer is invoked and throws an exception. |
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.
MyClass1 myClass1 = new MyClass1(); // Get the type referenced by the specified type handle. Type myClass1Type = Type.GetTypeFromHandle(Type.GetTypeHandle(myClass1)); Console.WriteLine("The Names of the Attributes :"+myClass1Type.Attributes);
public static RuntimeTypeHandle GetTypeHandle( |
o
MyClass1 myClass1 = new MyClass1(); // Get the handle for the specified object. RuntimeTypeHandle myClass1Type = Type.GetTypeHandle(myClass1); Console.WriteLine("Value :"+myClass1Type.Value); Console.WriteLine("Type :"+myClass1Type.GetType());
protected abstract bool HasElementTypeImpl(); |
public class MyTypeDelegator : TypeDelegator { public string myElementType = null; private Type myType = null ; public MyTypeDelegator(Type myType) : base(myType) { this.myType = myType; } // Overrides 'HasElementTypeImpl()' method of 'Type' class. protected override bool HasElementTypeImpl() { // Check whether the type is an array. if(myType.IsArray) { myElementType = "array"; return true; } // Check whether the type is a reference. if(myType.IsByRef) { myElementType = "reference"; return true; } // Check whether the type is a pointer. if(myType.IsPointer) { myElementType = "pointer"; return true; } // The type is not a reference or array or pointer type. return false; } } public class Type_HasElementTypeImpl { public static void Main() { try { int myInt = 0 ; int[] myArray = new int[5]; MyTypeDelegator myType = new MyTypeDelegator(myArray.GetType()); Console.WriteLine("\nCheck whether a variable refers to an array or pointer or reference type.\n"); // Check if 'myType' is an array, pointer, reference type. if( myType.HasElementType) Console.WriteLine("'myArray' is an {0}", myType.myElementType); else Console.WriteLine("'myArray' does not refer to an array or pointer or reference"); myType = new MyTypeDelegator(myInt.GetType()); // Check if 'myType' is an array, pointer, reference type. if( myType.HasElementType) Console.WriteLine("'myInt' is an {0}", myType.myElementType); else Console.WriteLine("'myInt' does not refer to an array or pointer or reference"); } catch( Exception e ) { Console.WriteLine("Exception: {0}", e.Message); } } }
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 abstract 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
modifiers
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.
namedParameters
Exception Type | Condition |
---|---|
ArgumentNullException | invokeAttr contains CreateInstance and typeName is null. |
ArgumentException | args is multidimensional. -or- modifiers is multidimensional. -or- args and modifiers do not have the same length. -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- The named parameter array is larger than the argument array. -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. |
Although the default binder does not process ParameterModifier or CultureInfo (the modifiers and culture parameters), you can use the abstract Binder class to write a custom binder that does process modifiers and culture.ParameterModifier is only used when calling through COM interop, and only parameters that are passed by reference are handled.
The args array and the modifiers array have the same length. A parameter specified in the args 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.
Each parameter in the namedParameters array gets the value in the corresponding element in the args array. If the length of args is greater than the length of namedParameters, the remaining argument values are passed in order.
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.
InvokeMember can be used to invoke methods with parameters that have default values. To bind to these methods, Reflection requires one of the binding flags DefaultValueBinding, DefaultValueChangeType, or DefaultValueFull to be specified explicitly. This is a requirement even in those cases where a value is passed for a parameter that has a default value.
For example, consider a method such as MyMethod(int x, float y = 2.0). To invoke this method with only the first argument as MyMethod(4), pass one of the above binding flags and pass two arguments, namely, 4 for the first argument and Missing.Value for the second argument. Unless you use Missing.Value, you may not omit optional parameters with the Invoke method. If you must do so, use InvokeMember instead.
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 {}
protected abstract bool IsArrayImpl(); |
public class MyTypeDelegator : TypeDelegator { public string myElementType = null; public Type myType; public MyTypeDelegator(Type myType) : base(myType) { this.myType = myType; } // Overrides 'IsArrayImpl()' method of 'Type' class. protected override bool IsArrayImpl() { // Check whether type is an array. if(myType.IsArray) { myElementType = "array"; return true; } // Type is not an array. return false; } } public class Type_IsArrayImpl { public static void Main() { try { int myInt = 0 ; // An array element. int[] myArray = new int[5]; MyTypeDelegator myType = new MyTypeDelegator(myArray.GetType()); Console.WriteLine("\nCheck if the variable is an array\n"); // Check if 'myType' is an array type. if( myType.IsArray) Console.WriteLine(" 'myArray' is an {0} ", myType.myElementType); else Console.WriteLine(" 'myArray' is not an array "); myType = new MyTypeDelegator(myInt.GetType()); // Check if 'myType' is an array type. if( myType.IsArray) Console.WriteLine(" 'myInt' is an ", myType.myElementType); else Console.WriteLine(" 'myInt' is not an array"); } catch( Exception e ) { Console.WriteLine("Exception : {0}", e.Message ); } } }
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 abstract bool IsByRefImpl(); |
protected abstract bool IsCOMObjectImpl(); |
This method returns false for COM interfaces because they are not objects. COM interfaces can be implemented by Microsoft .NET Framework objects.
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
using System; using System.Reflection; // Define a custom attribute with one named parameter. [AttributeUsage(AttributeTargets.All)] public class MyAttribute : Attribute { private string myName; public MyAttribute(string name) { myName = name; } public string Name { get { return myName; } } } // Define a class which has the custom attribute associated with one of its members. public class MyClass1 { [MyAttribute("This is an example attribute")] public void MyMethod(int i) { return; } } public class MemberInfo_GetCustomAttributes_IsDefined { public static void Main() { try { // Get the type of the class 'MyClass1'. Type myType = typeof(MyClass1); // Get the members associated with the class 'MyClass1'. MemberInfo[] myMembers = myType.GetMembers(); // Display the attributes for each of the members of the class 'MyClass1'. for(int i = 0; i < myMembers.Length; i++) { // Display the attribute if it is of type 'MyAttribute'. if(myMembers[i].IsDefined(typeof(MyAttribute), false)) { Object[] myAttributes = myMembers[i].GetCustomAttributes(typeof(MyAttribute), false); Console.WriteLine("\nThe attributes of type 'MyAttribute' for the member {0} are : \n", myMembers[i]); for(int j = 0; j < myAttributes.Length; j++) // Display the value associated with the attribute. Console.WriteLine("The value of the attribute is : \"{0}\"", ((MyAttribute)myAttributes[j]).Name); } } } catch(Exception e) { Console.WriteLine("Exception Caught! "+e.Message); } } }
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 abstract bool IsPointerImpl(); |
protected abstract bool IsPrimitiveImpl(); |
public class MyTypeDelegatorClass : TypeDelegator { public string myElementType = null; private Type myType = null ; public MyTypeDelegatorClass(Type myType) : base(myType) { this.myType = myType; } // Override 'IsPrimitiveImpl' method of 'Type' class. protected override bool IsPrimitiveImpl() { // Check whether the type is a primitive type. if(myType.IsPrimitive) { myElementType = "primitive"; return true; } return false; } } public class MyTypeDemoClass { public static void Main() { try { Console.WriteLine ("Check whether 'int' is a primitive type"); MyTypeDelegatorClass myType; myType = new MyTypeDelegatorClass(typeof(int)); // Check if 'int' type is a primitive type. if( myType.IsPrimitive) { Console.WriteLine(typeof(int) + " is a primitive type."); } else { Console.WriteLine(typeof(int) + " is not a primitive type."); } Console.WriteLine ("\nCheck whether 'string' is a primitive type"); myType = new MyTypeDelegatorClass(typeof(string)); // Check if 'string' type is a primitive type. if( myType.IsPrimitive) { Console.WriteLine(typeof(string) + " is a primitive type."); } else { Console.WriteLine(typeof(string) + " is not a primitive type."); } } catch( Exception e ) { Console.WriteLine("Exception: {0}", e.Message); } } }
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 virtual bool IsValueTypeImpl(); |
public class MyTypeDelegator : TypeDelegator { public string myElementType = null; private Type myType = null ; public MyTypeDelegator(Type myType) : base(myType) { this.myType = myType; } // Override 'IsValueTypeImpl()' method of 'Type' class. protected override bool IsValueTypeImpl() { // Check whether the type is an value type. if(myType.IsValueType) { myElementType = "value"; return true; } // The type is not value type. return false; } } public class Type_IsValueTypeImpl { public class MyClass { } public static void Main() { try { int myInt = 0 ; MyClass myClass = new MyClass (); MyTypeDelegator myType = new MyTypeDelegator(myInt.GetType()); Console.WriteLine("\nCheck whether a variable refers to a value type.\n"); // Check if 'myType' is a value type. if( myType.IsValueType) Console.WriteLine("\n'myInt' is a {0} type.", myType.myElementType); else Console.WriteLine("\n'myInt' is not a value type."); myType = new MyTypeDelegator(myClass.GetType()); // Check if 'myType' is a value type. if( myType.IsValueType) Console.WriteLine("\n'myClass' is a {0} type.", myType.myElementType); else Console.WriteLine("\n'myClass' is not a value type."); } catch( Exception e ) { Console.WriteLine("\nThe following exception is raised:" +e.Message); } } }
protected object MemberwiseClone(); |
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 ); } } }