System.Type Class

Assembly: Mscorlib.dll
Namespace: System
Summary
Represents type declarations: class types, interface types, array types, value types, and enumeration types.
C# Syntax:
[Serializable]
public abstract class Type : MemberInfo, IReflect
Thread Safety
This type is safe for multithreaded operations.
Remarks
Type is the root of all reflection operations and the object that represents a type inside the system.Type is an abstract base class that allows multiple implementations. The system will always provide the derived class RuntimeType. In reflection, all classes beginning with the word Runtime are created only once per object in the system and support comparison operations.

Notes to inheritors: When you inherit from Type, you must override the following members: Type.GUID, InvokeMember, Type.Module, Type.Assembly, Type.TypeHandle, Type.FullName, Type.Namespace, Type.AssemblyQualifiedName, Type.BaseType, Type.GetConstructorImpl, GetConstructors, Type.GetMethodImpl, GetMethods, GetField, GetFields, GetInterface, Type.GetInterfaces, GetEvent, GetEvents, Type.GetPropertyImpl, GetProperties, GetNestedType, GetNestedTypes, Type.GetAttributeFlagsImpl, Type.IsArrayImpl, Type.IsByRefImpl, Type.IsPointerImpl, Type.IsPrimitiveImpl, Type.IsCOMObjectImpl, Type.GetElementType, Type.HasElementTypeImpl, Type.UnderlyingSystemType, MemberInfo.Name, MemberInfo.IsDefined, System.Reflection.MemberInfo.GetCustomAttributes, and System.Reflection.MemberInfo.GetCustomAttributes.

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.



Note on Security: A derived class can access protected members of the calling code's base classes. Also, access is allowed to assembly members of the calling code's assembly. As a rule, if you are allowed access in early bound code, then you are also allowed access in late bound code.

Note on Reflection over Interfaces: Interfaces that extend other interfaces do not inherit the methods defined in the extended interfaces.
See also:
System Namespace | Object | System.Reflection | ReflectionPermission

System.Type Member List:

Public Fields
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.
Public Properties
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.
Public Methods
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.GetCustomAttributes


When 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.GetCustomAttributes


When 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.GetType

Derived 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.
Protected Constructors
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.
Protected Methods
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:


System.Type Member Details

ctor #1
Summary
Initializes a new instance of the Type class.

Default constructor. This constructor is called by derived class constructors to initialize state in this type.
C# Syntax:
protected Type();
Remarks
This constructor is invoked by derived classes during the construction of type objects.

Return to top


Field: Delimiter
Summary
Separates names in the namespace of the Type. This field is read-only.
C# Syntax:
public static readonly char Delimiter;
Example
The following code example shows the Delimiter field used in a resource name.
typeNameSpace + Type.Delimiter + baseName + '.' + cultureName [+ '-' + subCultureName] + '.resources'

    

Return to top


Field: EmptyTypes
Summary
Represents an empty array of type Type. This field is read-only.
C# Syntax:
public static readonly Type[] EmptyTypes;
Example
The following code example shows the EmptyTypes field used in one of the GetConstructor methods to get a constructor that takes no parameters.
cInfo = type.GetConstructor (BindingFlags.ExactBinding, null, 
         Type.EmptyTypes, null);

    

Return to top


Field: FilterAttribute
Summary
Represents the member filter used on attributes. This field is read-only.
C# Syntax:
public static readonly MemberFilter FilterAttribute;
Remarks
This field holds a reference to the delegate used by the Type.FindMembers method. The method encapsulated by this delegate takes two parameters: the first is a MemberInfo object and the second is an Object. The method determines whether the MemberInfo object matches the criteria specified by the Object. The Object may be assigned the value of any one of the fields on the classes FieldAttributes, MethodAttributes, or MethodImplAttributes.

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.

Example
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); 
      } 
   }	
}

    
See also:
Type.FindMembers | MemberFilter

Return to top


Field: FilterName
Summary
Represents the case-sensitive member filter used on names. This field is read-only.
C# Syntax:
public static readonly MemberFilter FilterName;
Remarks
This field holds a reference to the delegate used by the Type.FindMembers method. The method encapsulated by this delegate takes two parameters: the first is a MemberInfo object and the second is an Object. The method determines whether the MemberInfo object matches the criteria specified by the Object. The Object is assigned a string value, which may include a trailing "*" wildcard character. Only wildcard end string matching is supported.

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".

Example
The following code example gets the set of methods associated with the user-defined Application type.
 // 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);

    
See also:
Type.FindMembers | MemberFilter

Return to top


Field: FilterNameIgnoreCase
Summary
Represents the case-insensitive member filter used on names. This field is read-only.
C# Syntax:
public static readonly MemberFilter FilterNameIgnoreCase;
Remarks
This field holds a reference to the delegate used by the Type.FindMembers method. The method encapsulated by this delegate takes two parameters: the first is a MemberInfo object and the second is an Object. The method determines whether the MemberInfo object matches the criteria specified by the Object. The Object is assigned a string value, which may include a trailing "*" wildcard character. Only wildcard end string matching is supported.

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.

Example
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); 
      }
   }
}

    
See also:
Type.FindMembers | MemberFilter

Return to top


Field: Missing
Summary
Represents a missing value in the Type information. This field is read-only.
C# Syntax:
public static readonly object Missing;
Remarks
Use the Missing field for invocation through reflection to obtain the default value of a parameter. If the Missing field is passed in for a parameter value and there is no default value for that parameter, an ArgumentException is thrown.
Example
The following code example shows the use of the Missing field to invoke a method with its default arguments.

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

See also:
Missing | MSDN: accessingdefaultargumentvalues

Return to top


Property: Assembly (read-only)
Summary
Gets the Assembly that the type is declared in.
C# Syntax:
public abstract Assembly Assembly {get;}
Remarks
This property is read-only.
Example
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()); 
    }
}

    

Return to top


Property: AssemblyQualifiedName (read-only)
Summary
Gets the fully qualified name of the Type, including the name of the assembly from which the Type was loaded.
C# Syntax:
public abstract string AssemblyQualifiedName {get;}
Remarks
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.

Example
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()); 
    }
}

    
See also:
String | Type.GetType | Type.FullName | Type.Namespace | MSDN: specifyingfullyqualifiedtypenames | AssemblyName

Return to top


Property: Attributes (read-only)
Summary
Gets the attributes associated with the Type.
C# Syntax:
public TypeAttributes Attributes {get;}
Example
See also:
Type.GetAttributeFlagsImpl | TypeAttributes

Return to top


Property: BaseType (read-only)
Summary
Gets the type from which the current Type directly inherits.
C# Syntax:
public abstract Type BaseType {get;}
Remarks
The base type is the type from which the current type directly inherits. Object is the only type that does not have a base type, therefore null is returned as the base type of Object.

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.

Example
The following example demonstrates using the BaseType property.
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
See also:
Object | Type.GetInterfaces | Type.FindInterfaces | Type.UnderlyingSystemType | Type.IsSubclassOf

Return to top


Overridden Property: DeclaringType (read-only)
Summary
Gets the class that declares this member.
C# Syntax:
public override Type DeclaringType {get;}
Remarks
This property implements the abstract property inherited from MemberInfo.
Example
This example displays the declaring type of a method in a derived class.
 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

See also:
MemberInfo | Type.ReflectedType

Return to top


Property: DefaultBinder (read-only)
Summary
Gets the default binder used by the system.
C# Syntax:
public static Binder DefaultBinder {get;}
Remarks
Reflection models the accessibility rules of the common type system. For example, if the caller is in the same assembly, the caller does not need special permissions for internal members. Otherwise, the caller needs ReflectionPermission. This is consistent with lookup of members that are protected, private, and so on.

The general principle is that 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.
Example
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");
		}	
	}
}

    
See also:
Binder

Return to top


Property: FullName (read-only)
Summary
Gets the fully qualified name of the Type, including the namespace of the Type.
C# Syntax:
public abstract string FullName {get;}
Remarks
For example, the fully qualified name of the C# string type is System.String.

This property is read-only.

Example
The following example demonstrates using the FullName property.
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

See also:
String | Type.Namespace | Type.AssemblyQualifiedName | MSDN: specifyingfullyqualifiedtypenames | AssemblyName

Return to top


Property: GUID (read-only)
Summary
Gets the GUID associated with the Type.
C# Syntax:
public abstract Guid GUID {get;}
Example
      // 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);				

    
See also:
Guid

Return to top


Property: HasElementType (read-only)
Summary
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.
C# Syntax:
public bool HasElementType {get;}
Remarks
For example, Type.GetType("Int32[]").HasElementType returns true, but Type.GetType("Int32").HasElementType returns false. HasElementType also returns true for "Int32*" and "Int32&".
Example

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 ) ; 
      }	
   }
}

    
See also:
Type.HasElementTypeImpl | Type.IsArray | Type.IsPointer | Type.IsByRef | Type.GetElementType | Type.GetType

Return to top


Property: IsAbstract (read-only)
Summary
Gets a value indicating whether the Type is abstract and must be overridden.
C# Syntax:
public bool IsAbstract {get;}
Example

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 ); 
      }
   }
}

    
See also:
TypeAttributes

Return to top


Property: IsAnsiClass (read-only)
Summary
Gets a value indicating whether the string format attribute AnsiClass is selected for the Type.
C# Syntax:
public bool IsAnsiClass {get;}
Remarks
The TypeAttributes.StringFormatMask selects the string format attributes. The string format attributes enhance interoperability by defining how strings should be interpreted.
Example
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);
      }
   }
}

    
See also:
TypeAttributes | Type.IsUnicodeClass | Type.IsAutoClass

Return to top


Property: IsArray (read-only)
Summary
Gets a value indicating whether the Type is an array.
C# Syntax:
public bool IsArray {get;}
Remarks
The Array class returns false because it is not an array.

This property is read-only.

Example
The following example demonstrates using the IsArray property.
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
              			
            
See also:
Type.IsArrayImpl

Return to top


Property: IsAutoClass (read-only)
Summary
Gets a value indicating whether the string format attribute AutoClass is selected for the Type.
C# Syntax:
public bool IsAutoClass {get;}
Remarks
The TypeAttributes.StringFormatMask selects the string format attributes. The string format attributes enhance interoperability by defining how strings should be interpreted.
See also:
TypeAttributes | Type.IsAnsiClass | Type.IsUnicodeClass

Return to top


Property: IsAutoLayout (read-only)
Summary
Gets a value indicating whether the class layout attribute AutoLayout is selected for the Type.
C# Syntax:
public bool IsAutoLayout {get;}
Remarks
The TypeAttributes.LayoutMask is used to select the class layout attributes. The class layout attributes (AutoLayout,SequentialLayout and ExplicitLayout) define how the fields of the class instance are laid out in memory.

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.

Example
// 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);
      }
   }
}

    
See also:
TypeAttributes | Type.IsLayoutSequential | Type.IsExplicitLayout | MSDN: metadataoverview

Return to top


Property: IsByRef (read-only)
Summary
Gets a value indicating whether the Type is passed by reference.
C# Syntax:
public bool IsByRef {get;}
See also:
Type.IsByRefImpl

Return to top


Property: IsClass (read-only)
Summary
Gets a value indicating whether the Type is a class; that is, not a value type or interface.
C# Syntax:
public bool IsClass {get;}
Remarks
This property returns true for Type instances representing Enum and ValueType.

The TypeAttributes.ClassSemanticsMask distinguishes a type declaration as class, interface, or value type.

This property is read-only.

Example
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);
      }
   }
}

    
See also:
TypeAttributes | Type.IsInterface | Type.IsValueType

Return to top


Property: IsCOMObject (read-only)
Summary
Gets a value indicating whether the Type is a COM object.
C# Syntax:
public bool IsCOMObject {get;}
Remarks
This method returns false for COM interfaces because they are not objects. COM interfaces can be implemented by Microsoft .NET Framework objects.

You can also load a COM class and get a Type object for that COM class by using the tool.

See also:
Type.IsCOMObjectImpl

Return to top


Property: IsContextful (read-only)
Summary
Gets a value indicating whether the Type can be hosted in a context.
C# Syntax:
public bool IsContextful {get;}
Remarks
A context intercepts calls to the class members and enforces policies that are applied to the class, such as synchronization. For more detailed information on remoting contexts, see Context.
Example

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);
      }
   }
}

    
See also:
Type.IsContextfulImpl

Return to top


Property: IsEnum (read-only)
Summary
Gets a value indicating whether the current Type represents an enumeration.
C# Syntax:
public bool IsEnum {get;}
Remarks
This property returns true for an enumeration, but not for the Enum type itself, which is a class.

This property is read-only.

Example
The following example demonstrates using the IsEnum property.
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
              			
            
See also:
TypeAttributes

Return to top


Property: IsExplicitLayout (read-only)
Summary
Gets a value indicating whether the class layout attribute ExplicitLayout is selected for the Type.
C# Syntax:
public bool IsExplicitLayout {get;}
Remarks
The TypeAttributes.LayoutMask is used to select the class layout attributes. The class layout attributes (AutoLayout,SequentialLayout and ExplicitLayout) define how the fields of the class instance are laid out in memory.

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.

Example
//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);
      }
   }
}

    
See also:
TypeAttributes | Type.IsAutoLayout | Type.IsLayoutSequential | MSDN: metadataoverview

Return to top


Property: IsImport (read-only)
Summary
Gets a value indicating whether the Type was imported from another class.
C# Syntax:
public bool IsImport {get;}
See also:
TypeAttributes

Return to top


Property: IsInterface (read-only)
Summary
Gets a value indicating whether the Type is an interface; that is, not a class or a value type.
C# Syntax:
public bool IsInterface {get;}
Remarks
The TypeAttributes.ClassSemanticsMask distinguishes a type declaration as class, interface or value type.

This property is read-only.

Example
// 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);
      }
   }
}

    
See also:
TypeAttributes | Type.IsClass | Type.IsValueType

Return to top


Property: IsLayoutSequential (read-only)
Summary
Gets a value indicating whether the class layout attribute SequentialLayout is selected for the Type.
C# Syntax:
public bool IsLayoutSequential {get;}
Remarks
The TypeAttributes.LayoutMask is used to select the class layout attributes. The class layout attributes (AutoLayout,SequentialLayout and ExplicitLayout) define how the fields of the class instance are laid out in memory.

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.

Example
// 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);
      }
   }
}

    
See also:
TypeAttributes | Type.IsAutoLayout | Type.IsExplicitLayout | MSDN: metadataoverview

Return to top


Property: IsMarshalByRef (read-only)
Summary
Gets a value indicating whether the Type is marshaled by reference.
C# Syntax:
public bool IsMarshalByRef {get;}
Example

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);
      }
   }
}

    
See also:
Type.IsMarshalByRefImpl

Return to top


Property: IsNestedAssembly (read-only)
Summary
Gets a value indicating whether the Type is nested and visible only within its own assembly.
C# Syntax:
public bool IsNestedAssembly {get;}
Remarks
The TypeAttributes.VisibilityMask selects the visibility attributes.
Example
// 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());
   }
}

    
See also:
TypeAttributes

Return to top


Property: IsNestedFamANDAssem (read-only)
Summary
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.
C# Syntax:
public bool IsNestedFamANDAssem {get;}
Remarks
The TypeAttributes.VisibilityMask selects the visibility attributes.

A Type object's family is defined as all objects of the exact same Type and of its subtypes.

See also:
TypeAttributes

Return to top


Property: IsNestedFamily (read-only)
Summary
Gets a value indicating whether the Type is nested and visible only within its own family.
C# Syntax:
public bool IsNestedFamily {get;}
Remarks
The TypeAttributes.VisibilityMask selects the visibility attributes.

A Type object's family is defined as all objects of the exact same Type and of its subtypes.

Example
// 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());      
   }
}

    
See also:
TypeAttributes

Return to top


Property: IsNestedFamORAssem (read-only)
Summary
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.
C# Syntax:
public bool IsNestedFamORAssem {get;}
Remarks
The TypeAttributes.VisibilityMask selects the visibility attributes.

A Type object's family is defined as all objects of the exact same Type and of its subtypes.

Example
// 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()); 
   }
}

    
See also:
TypeAttributes

Return to top


Property: IsNestedPrivate (read-only)
Summary
Gets a value indicating whether the Type is nested and declared private.
C# Syntax:
public bool IsNestedPrivate {get;}
Remarks
The TypeAttributes.VisibilityMask selects the visibility attributes.
Example
// 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());	
   }
}

    
See also:
TypeAttributes

Return to top


Property: IsNestedPublic (read-only)
Summary
Gets a value indicating whether a class is nested and declared public.
C# Syntax:
public bool IsNestedPublic {get;}
Remarks
The TypeAttributes.VisibilityMask selects the visibility attributes.
Example
The following example demonstrates the IsNestedPublic property. A nested class MyClassB is declared as public and the IsNestedPublic property value is displayed.

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());			
   }
}

    
See also:
TypeAttributes

Return to top


Property: IsNotPublic (read-only)
Summary
Gets a value indicating whether the top-level Type is not declared public.
C# Syntax:
public bool IsNotPublic {get;}
Remarks
IsPublic and IsNotPublic get the visibility of the top-level type only.

TypeAttributes.VisibilityMask selects the visibility attributes.

Example
This example shows the use of IsNotPublic to get the visibility of the top-level type.
 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
See also:
TypeAttributes

Return to top


Property: IsPointer (read-only)
Summary
Gets a value indicating whether the Type is a pointer.
C# Syntax:
public bool IsPointer {get;}
Remarks
This property is read-only.
See also:
Type.IsPointerImpl

Return to top


Property: IsPrimitive (read-only)
Summary
Gets a value indicating whether the Type is one of the primitive types.
C# Syntax:
public bool IsPrimitive {get;}
Remarks
The primitive types are Boolean, Byte, SByte, Int16, UInt16, Int32, UInt32, Int64, UInt64, Char, Double, and Single.
Example
         // 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);

    
See also:
Boolean | Byte | SByte | Int16 | UInt16 | Int32 | UInt32 | Int64 | UInt64 | Char | Double | Single | Type.IsPrimitiveImpl

Return to top


Property: IsPublic (read-only)
Summary
Gets a value indicating whether the top-level Type is declared public.
C# Syntax:
public bool IsPublic {get;}
Remarks
IsPublic and IsNotPublic get the visibility of the top-level type only.

TypeAttributes.VisibilityMask selects the visibility attributes.

Example
This example shows the use of IsPublic to get the visibility of the top-level type.
 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
See also:
TypeAttributes

Return to top


Property: IsSealed (read-only)
Summary
Gets a value indicating whether the Type is declared sealed.
C# Syntax:
public bool IsSealed {get;}
Example
      // 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);
         }
      }

    
See also:
TypeAttributes

Return to top


Property: IsSerializable (read-only)
Summary
Gets a value indicating whether the Type is serializable.
C# Syntax:
public bool IsSerializable {get;}
Example
      // 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);
         }
      }

    
See also:
TypeAttributes | ISerializable

Return to top


Property: IsSpecialName (read-only)
Summary
Gets a value indicating whether the Type has a name that requires special handling.
C# Syntax:
public bool IsSpecialName {get;}
Remarks
Names that begin with or contain an underscore character (_), property accessors, and operator overloading methods are examples of types that might require special treatment by some compilers.
Example
This example shows a use of IsSpecialName to filter internal or private members out of a list.
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)");
      }
 }

    
See also:
TypeAttributes

Return to top


Property: IsUnicodeClass (read-only)
Summary
Gets a value indicating whether the string format attribute UnicodeClass is selected for the Type.
C# Syntax:
public bool IsUnicodeClass {get;}
Remarks
The TypeAttributes.StringFormatMask is used to select the string format attributes. The string format attributes enhance interoperability by defining how strings should be interpreted.
See also:
TypeAttributes | Type.IsAnsiClass | Type.IsAutoClass

Return to top


Property: IsValueType (read-only)
Summary
Gets a value indicating whether the Type is a value type.
C# Syntax:
public bool IsValueType {get;}
Remarks
Value types are those that are represented as sequences of bits; value types are not classes or interfaces. These are referred to as "structs" in some programming languages. Enums are a special case of value types.

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.

Example
      // 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);
         }
      }

    
See also:
TypeAttributes | Type.IsClass | Type.IsInterface | ValueType | Type.IsValueTypeImpl | TypeAttributes | Type.IsClass | Type.IsInterface | ValueType | Type.IsValueTypeImpl

Return to top


Overridden Property: MemberType (read-only)
Summary
Gets a bitmask indicating the member type.
C# Syntax:
public override MemberTypes MemberType {get;}
Example
The following code example shows the MemberType field as a parameter to the GetMember method:
MemberInfo[] others = t.GetMember(mi.Name, mi.MemberType, BindingFlags.Public |
BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Instance);

    
See also:
MemberTypes

Return to top


Property: Module (read-only)
Summary
Gets the module (the DLL) in which the current Type is defined.
C# Syntax:
public abstract Module Module {get;}
See also:
Module

Return to top


Property: Name (read-only)
Inherited
See base class member description: System.Reflection.MemberInfo.Name

Summary
Gets the name of this member.
C# Syntax:
public abstract string Name {get;}
Remarks
Only the simple name is returned, not the fully qualified name. For example, for a member System.Reflection.MemberTypes.Field, the Name property would be Field.

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.

Example
This example lists the Name and DeclaringType property of each member of the System.Empty class.
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
 */

    

Return to top


Property: Namespace (read-only)
Summary
Gets the namespace of the Type.
C# Syntax:
public abstract string Namespace {get;}
Remarks
A namespace is a logical design-time naming convenience, used mainly to define scope in an application and organize classes and other types in a single hierarchical structure. From the viewpoint of the runtime, there are no namespaces.
See also:
String | Type.FullName | Type.AssemblyQualifiedName | MSDN: specifyingfullyqualifiedtypenames

Return to top


Overridden Property: ReflectedType (read-only)
Summary
Gets the class object that was used to obtain this member.
C# Syntax:
public override Type ReflectedType {get;}
Remarks
This property implements the abstract property inherited from MemberInfo.
Example
This example displays the reflected type of a method in a derived class. Although the method m is declared in MyClassA, its reflected type is obtained from MyClassB.
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

See also:
MemberInfo | Type.DeclaringType

Return to top


Property: TypeHandle (read-only)
Summary
Gets the handle for the current Type.
C# Syntax:
public abstract RuntimeTypeHandle TypeHandle {get;}
Remarks
TypeHandle encapsulates a pointer to an internal data structure that represents the type. This handle is unique during the process lifetime. The handle is valid only in the application domain in which it was obtained.
Example
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());
   }
}

    
See also:
RuntimeTypeHandle | Type.GetTypeHandle | Type.GetTypeFromHandle

Return to top


Property: TypeInitializer (read-only)
Summary
Gets the initializer for the Type.
C# Syntax:
public ConstructorInfo TypeInitializer {get;}
Remarks
Class initializers are available through Type.GetMember, Type.GetMembers, Type.FindMembers, and Type.GetConstructors.
See also:
ConstructorInfo

Return to top


Property: UnderlyingSystemType (read-only)
Summary
Indicates the type provided by the common language runtime that represents this type.
C# Syntax:
public abstract Type UnderlyingSystemType {get;}
Implements:
IReflect.UnderlyingSystemType
See also:
Type.BaseType

Return to top


Overloaded Method: Equals(
   object o
)
Summary
Determines if the underlying system type of the current Type is the same as the underlying system type of the specified Object.
C# Syntax:
public override bool Equals(
   object o
);
Parameters:

o

The Object whose underlying system type is to be compared with the underlying system type of the current Type.

Return Value:
true if the underlying system type of o is the same as the underlying system type of the current Type; otherwise, false. This method also returns false if the object specified by the o parameter is not a Type.
Remarks
This method overrides Object.Equals.
Example
The following example uses Equals to compare two Object instances.
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

    
See also:
Type.UnderlyingSystemType

Return to top


Overloaded Method: Equals(
   Type o
)
Summary
Determines if the underlying system type of the current Type is the same as the underlying system type of the specified Type.
C# Syntax:
public bool Equals(
   Type o
);
Parameters:

o

The Type whose underlying system type is to be compared with the underlying system type of the current Type.

Return Value:
true if the underlying system type of o is the same as the underlying system type of the current Type; otherwise, false.
Example
The following example uses Equals to compare two types.
 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

    
See also:
Type.UnderlyingSystemType

Return to top


Method: Finalize()
Inherited
See base class member description: System.Object.Finalize
C# Syntax:
~Type();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: FindInterfaces(
   TypeFilter filter,
   object filterCriteria
)
Summary
Returns an array of Type objects representing a filtered list of interfaces implemented or inherited by the current Type.
C# Syntax:
public virtual Type[] FindInterfaces(
   TypeFilter filter,
   object filterCriteria
);
Parameters:

filter

The TypeFilter delegate that compares the interfaces against filterCriteria. The TypeFilter delegate that compares the interfaces against filterCriteria.

filterCriteria

The search criteria that determines whether an interface should be included in the returned array.

Return Value:
An array of Type objects representing a filtered list of the interfaces implemented or inherited by the current Type.

-or-

An empty array of type Type, if no interfaces matching the filter are implemented or inherited by the current Type.

Exceptions
Exception Type Condition
ArgumentNullException filter is null.
TargetInvocationException A static initializer is invoked and throws an exception.
Remarks
This method can be overridden by a derived class.

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.

Example
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;
	}
}

    
See also:
Module | TypeFilter | Type.GetInterface | Type.GetInterfaces

Return to top


Method: FindMembers(
   MemberTypes memberType,
   BindingFlags bindingAttr,
   MemberFilter filter,
   object filterCriteria
)
Summary
Returns a filtered array of MemberInfo objects of the specified member type.
C# Syntax:
public virtual MemberInfo[] FindMembers(
   MemberTypes memberType,
   BindingFlags bindingAttr,
   MemberFilter filter,
   object filterCriteria
);
Parameters:

memberType

A MemberTypes object indicating the type of member to search for.

bindingAttr

A bitmask comprised of one or more BindingFlags that specify how the search is conducted.

-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

The delegate that does the comparisons, returning true if the member currently being inspected matches the filterCriteria and false otherwise. You can use the FilterAttribute, FilterName, and FilterNameIgnoreCase delegates supplied by this class. The first uses the fields of FieldAttributes, MethodAttributes, and MethodImplAttributes as search criteria, and the other two delegates use String objects as the search criteria.

filterCriteria

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.

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.

Return Value:
A filtered array of MemberInfo objects of the specified member type.

-or-

An empty array of type MemberInfo, if the current Type does not have members of type memberType that match the filter criteria.

Exceptions
Exception Type Condition
ArgumentNullException filter is null.
Remarks
This method can be overridden by a derived class.

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.

Example

.NET Framework Security:
ReflectionPermission for reflecting non-public objects. Associated enumeration: ReflectionPermissionFlag.TypeInformation
See also:
MemberInfo | BindingFlags | Type.DefaultBinder | ReflectionPermission | Type.GetMember | Type.GetMembers | Type.GetDefaultMembers

Return to top


Method: GetArrayRank()
Summary
Gets the number of dimensions in an Array.
C# Syntax:
public virtual int GetArrayRank();
Return Value:
An Int32 containing the number of dimensions in the current Type.
Exceptions
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.
Example
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);
      }      
   }
}

    
See also:
Array | Array.Rank

Return to top


Method: GetAttributeFlagsImpl()
Summary
When overridden in a derived class, implements the Type.Attributes property and gets a bitmask indicating the attributes associated with the Type.
C# Syntax:
protected abstract TypeAttributes GetAttributeFlagsImpl();
Return Value:
A TypeAttributes object representing the attribute set of the Type.
See also:
Type.Attributes | TypeAttributes

Return to top


Overloaded Method: GetConstructor(
   Type[] types
)
Summary
Searches for a public instance constructor whose parameters match the types in the specified array.
C# Syntax:
public ConstructorInfo GetConstructor(
   Type[] types
);
Parameters:

types

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-

Type.EmptyTypes.

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-

Type.EmptyTypes.

Return Value:
A ConstructorInfo object representing the public instance constructor whose parameters match the types in the parameter type array, if found; otherwise, null.
Exceptions
Exception Type Condition
ArgumentNullException types is null.

-or-

One of the elements in types is null.

ArgumentException types is multidimensional.
Remarks
Type.GetConstructor looks for public instance constructors and 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.



Note You cannot omit parameters when looking up constructors and methods. You can only omit parameters when invoking.
Example

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);
      }
   }
}

    
.NET Framework Security:
ReflectionPermission for reflecting non-public objects. Associated enumeration: ReflectionPermissionFlag.TypeInformation
See also:
ConstructorInfo | Type.DefaultBinder | ReflectionPermission | Type.GetConstructorImpl | Type.GetConstructors

Return to top


Overloaded Method: GetConstructor(
   BindingFlags bindingAttr,
   Binder binder,
   Type[] types,
   ParameterModifier[] modifiers
)
Summary
Searches for a constructor whose parameters match the specified argument types and modifiers, using the specified binding constraints.
C# Syntax:
public ConstructorInfo GetConstructor(
   BindingFlags bindingAttr,
   Binder binder,
   Type[] types,
   ParameterModifier[] modifiers
);
Parameters:

bindingAttr

A bitmask comprised of one or more BindingFlags that specify how the search is conducted.

-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

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.

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

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-

Type.EmptyTypes.

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-

Type.EmptyTypes.

modifiers

An array of ParameterModifier objects representing the attributes associated with the corresponding element in the parameter type array. The default binder does not process this parameter.

Return Value:
A ConstructorInfo object representing the constructor that matches the specified requirements, if found; otherwise, null.
Exceptions
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.

Remarks
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.

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.

Note You cannot omit parameters when looking up constructors and methods. You can only omit parameters when invoking.
Example
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);
      }
   }
}

    
.NET Framework Security:
ReflectionPermission for reflecting non-public objects. Associated enumeration: ReflectionPermissionFlag.TypeInformation
See also:
ConstructorInfo | BindingFlags | Binder | Type.DefaultBinder | ParameterModifier | ReflectionPermission | Type.GetConstructorImpl | Type.GetConstructors

Return to top


Overloaded Method: GetConstructor(
   BindingFlags bindingAttr,
   Binder binder,
   CallingConventions callConvention,
   Type[] types,
   ParameterModifier[] modifiers
)
Summary
Searches for a constructor whose parameters match the specified argument types and modifiers, using the specified binding constraints and the specified calling convention.
C# Syntax:
public ConstructorInfo GetConstructor(
   BindingFlags bindingAttr,
   Binder binder,
   CallingConventions callConvention,
   Type[] types,
   ParameterModifier[] modifiers
);
Parameters:

bindingAttr

A bitmask comprised of one or more BindingFlags that specify how the search is conducted.

-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

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.

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

The CallingConventions object that specifies the set of rules to use regarding the order and layout of arguments, how the return value is passed, what registers are used for arguments, and the stack is cleaned up.

types

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.

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

An array of ParameterModifier objects representing the attributes associated with the corresponding element in the types array. The default binder does not process this parameter.

Return Value:
A ConstructorInfo object representing the constructor that matches the specified requirements, if found; otherwise, null.
Exceptions
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.

Remarks
Although the default binder does not process ParameterModifier (the modifiers parameter), you can use the abstract Binder class to write a custom binder that does process modifiers.ParameterModifier is only used when calling through COM interop, and only parameters that are passed by reference are handled.

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.
  1. Hide-by-name-and-signature considers all of the parts of the signature, including custom modifiers, return types, parameter types, sentinels, and unmanaged calling conventions. This is a binary comparison.
  2. For reflection, properties and events are hide-by-name-and-signature. If you have a property with both a get and a set accessor in the base class, but the derived class has only a get accessor, the derived class property hides the base class property, and you will not be able to access the setter on the base class.
  3. Custom attributes are not part of the common type system.


Note You cannot omit parameters when looking up constructors and methods. You can only omit parameters when invoking.
Example
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);
      }
   }
}

    
.NET Framework Security:
ReflectionPermission for reflecting non-public objects. Associated enumeration: ReflectionPermissionFlag.TypeInformation
See also:
ConstructorInfo | BindingFlags | Binder | Type.DefaultBinder | CallingConventions | ParameterModifier | ReflectionPermission | Type.GetConstructorImpl | Type.GetConstructors

Return to top


Method: GetConstructorImpl(
   BindingFlags bindingAttr,
   Binder binder,
   CallingConventions callConvention,
   Type[] types,
   ParameterModifier[] modifiers
)
Summary
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.
C# Syntax:
protected abstract ConstructorInfo GetConstructorImpl(
   BindingFlags bindingAttr,
   Binder binder,
   CallingConventions callConvention,
   Type[] types,
   ParameterModifier[] modifiers
);
Parameters:

bindingAttr

A bitmask comprised of one or more BindingFlags that specify how the search is conducted.

-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

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.

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

The CallingConventions object that specifies the set of rules to use regarding the order and layout of arguments, how the return value is passed, what registers are used for arguments, and the stack is cleaned up.

types

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.

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

An array of ParameterModifier objects representing the attributes associated with the corresponding element in the types array. The default binder does not process this parameter.

Return Value:
A ConstructorInfo object representing the constructor that matches the specified requirements, if found; otherwise, null.
Exceptions
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.

Remarks
Although the default binder does not process ParameterModifier (the modifiers parameter), you can use the abstract Binder class to write a custom binder that does process modifiers.ParameterModifier is only used when calling through COM interop, and only parameters that are passed by reference are handled.

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.

.NET Framework Security:
ReflectionPermission for reflecting non-public objects. Associated enumeration: ReflectionPermissionFlag.TypeInformation
See also:
ConstructorInfo | BindingFlags | Binder | Type.DefaultBinder | CallingConventions | ParameterModifier | ReflectionPermission | Type.GetConstructor | Type.GetConstructors

Return to top


Overloaded Method: GetConstructors()
Summary
Returns all the public constructors defined for the current Type.
C# Syntax:
public ConstructorInfo[] GetConstructors();
Return Value:
An array of ConstructorInfo objects representing all the public constructors defined for the current Type, including the type initializer if it is defined.

-or-

An empty array of type ConstructorInfo, if no public constructors are defined for the current Type.

Remarks
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.
  1. Hide-by-name-and-signature considers all of the parts of the signature, including custom modifiers, return types, parameter types, sentinels, and unmanaged calling conventions. This is a binary comparison.
  2. For reflection, properties and events are hide-by-name-and-signature. If you have a property with both a get and a set accessor in the base class, but the derived class has only a get accessor, the derived class property hides the base class property, and you will not be able to access the setter on the base class.
  3. Custom attributes are not part of the common type system.

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.

Example
This example shows the output of GetConstructors() from a class that has two instance constructors and one static constructor.
 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

See also:
ConstructorInfo | Type.GetConstructor

Return to top


Overloaded Method: GetConstructors(
   BindingFlags bindingAttr
)
Summary
When overridden in a derived class, searches for the constructors defined for the current Type, using the specified BindingFlags.
C# Syntax:
public abstract ConstructorInfo[] GetConstructors(
   BindingFlags bindingAttr
);
Parameters:

bindingAttr

A bitmask comprised of one or more BindingFlags that specify how the search is conducted.

-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.

Return Value:
An array of ConstructorInfo objects representing all constructors defined for the current Type that match the specified binding constraints, including the type initializer if it is defined.

-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.

Remarks
bindingAttr can be used to specify whether to return only public constructors or both public and non-public constructors.

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.

Example
This example shows the output of GetConstructors() from a class that has two instance constructors and one static constructor.
 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

.NET Framework Security:
ReflectionPermission for reflecting non-public objects. Associated enumeration: ReflectionPermissionFlag.TypeInformation
See also:
ConstructorInfo | BindingFlags | Type.DefaultBinder | ReflectionPermission | Type.GetConstructor

Return to top


Overloaded Method: GetCustomAttributes(
   bool inherit
)
Inherited
See base class member description: System.Reflection.MemberInfo.GetCustomAttributes

Summary
When overridden in a derived class, returns an array of all of the custom attributes.
C# Syntax:
public abstract object[] GetCustomAttributes(
   bool inherit
);
Parameters:

inherit

Specifies whether to search this member's inheritance chain to find the attributes.

Return Value:
An array of all the custom attributes, or an array with zero elements if no attributes are defined.
Implements:
ICustomAttributeProvider.GetCustomAttributes
Example

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);
      }
   }
}

    
See also:
Object | CustomAttributeBuilder

Return to top


Overloaded Method: GetCustomAttributes(
   Type attributeType,
   bool inherit
)
Inherited
See base class member description: System.Reflection.MemberInfo.GetCustomAttributes

Summary
When overridden in a derived class, returns an array of custom attributes identified by Type.
C# Syntax:
public abstract object[] GetCustomAttributes(
   Type attributeType,
   bool inherit
);
Parameters:

attributeType

The type of attribute to search for. Only attributes that are assignable to this type are returned.

inherit

Specifies whether to search this member's inheritance chain to find the attributes.

Return Value:
An array of custom attributes defined on this reflected member, or an array with zero (0) elements if no attributes are defined.
Exceptions
Exception Type Condition
TypeLoadException If the custom attribute type can not be loaded.
Implements:
ICustomAttributeProvider.GetCustomAttributes

Return to top


Method: GetDefaultMembers()
Summary
Searches for the members defined for the current Type whose DefaultMemberAttribute is set.
C# Syntax:
public virtual MemberInfo[] GetDefaultMembers();
Return Value:
An array of MemberInfo objects representing all default members of the current Type.

-or-

An empty array of type MemberInfo, if the current Type does not have default members.

Remarks
This method can be overridden by a derived class.

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.
  1. Hide-by-name-and-signature considers all of the parts of the signature, including custom modifiers, return types, parameter types, sentinels, and unmanaged calling conventions. This is a binary comparison.
  2. For reflection, properties and events are hide-by-name-and-signature. If you have a property with both a get and a set accessor in the base class, but the derived class has only a get accessor, the derived class property hides the base class property, and you will not be able to access the setter on the base class.
  3. Custom attributes are not part of the common type system.
Example

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);
      }
   }
}

    
See also:
MemberInfo | DefaultMemberAttribute | Type.GetMember | Type.GetMembers | Type.FindMembers

Return to top


Method: GetElementType()
Summary
When overridden in a derived class, returns the Type of the object encompassed or referred to by the current array, pointer or reference type.
C# Syntax:
public abstract Type GetElementType();
Return Value:
The Type of the object encompassed or referred to by the current array, pointer or reference type.

-or-

null if the current Type is not an array or a pointer, or is not passed by reference.

Remarks
For example, Type.GetType("Int32[]").GetElementType returns Int32.
Example
The following example demonstrates using the GetElementType method.
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
              			
            
See also:
Type.HasElementType

Return to top


Overloaded Method: GetEvent(
   string name
)
Summary
Returns the EventInfo object representing the specified event.
C# Syntax:
public EventInfo GetEvent(
   string name
);
Parameters:

name

The String containing the name of an event which is declared or inherited by the current Type.

Return Value:
The EventInfo object representing the specified event which is declared or inherited by the current Type, if found; otherwise, null.
Exceptions
Exception Type Condition
ArgumentNullException name is null.
Remarks
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.

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.
  1. Hide-by-name-and-signature considers all of the parts of the signature, including custom modifiers, return types, parameter types, sentinels, and unmanaged calling conventions. This is a binary comparison.
  2. For reflection, properties and events are hide-by-name-and-signature. If you have a property with both a get and a set accessor in the base class, but the derived class has only a get accessor, the derived class property hides the base class property, and you will not be able to access the setter on the base class.
  3. Custom attributes are not part of the common type system.
Example
			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");

    
.NET Framework Security:
ReflectionPermission for reflecting non-public objects. Associated enumeration: ReflectionPermissionFlag.TypeInformation
See also:
EventInfo | String | Type.DefaultBinder | Type.GetEvents

Return to top


Overloaded Method: GetEvent(
   string name,
   BindingFlags bindingAttr
)
Summary
When overridden in a derived class, returns the EventInfo object representing the specified event, using the specified binding constraints.
C# Syntax:
public abstract EventInfo GetEvent(
   string name,
   BindingFlags bindingAttr
);
Parameters:

name

The String containing the name of an event which is declared or inherited by the current Type.

bindingAttr

A bitmask comprised of one or more BindingFlags that specify how the search is conducted.

-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.

Return Value:
The EventInfo object representing the specified event which is declared or inherited by the current Type, if found; otherwise, null.
Exceptions
Exception Type Condition
ArgumentNullException name is null.
Remarks
The following BindingFlags filter flags can be used to define which events 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.

Example
         // 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");

    
.NET Framework Security:
ReflectionPermission for reflecting non-public objects. Associated enumeration: ReflectionPermissionFlag.TypeInformation
See also:
EventInfo | String | BindingFlags | Type.DefaultBinder | ReflectionPermission | Type.GetEvents

Return to top


Overloaded Method: GetEvents()
Summary
Returns all the public events that are declared or inherited by the current Type.
C# Syntax:
public virtual EventInfo[] GetEvents();
Return Value:
An array of EventInfo objects representing all the public events which are declared or inherited by the current Type.

-or-

An empty array of type EventInfo, if the current Type does not have public events.

Remarks
This method can be overridden by a derived class.

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.
  1. Hide-by-name-and-signature considers all of the parts of the signature, including custom modifiers, return types, parameter types, sentinels, and unmanaged calling conventions. This is a binary comparison.
  2. For reflection, properties and events are hide-by-name-and-signature. If you have a property with both a get and a set accessor in the base class, but the derived class has only a get accessor, the derived class property hides the base class property, and you will not be able to access the setter on the base class.
  3. Custom attributes are not part of the common type system.
Example
         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());
         }

    
See also:
EventInfo | Type.GetEvent

Return to top


Overloaded Method: GetEvents(
   BindingFlags bindingAttr
)
Summary
When overridden in a derived class, searches for events that are declared or inherited by the current Type, using the specified binding constraints.
C# Syntax:
public abstract EventInfo[] GetEvents(
   BindingFlags bindingAttr
);
Parameters:

bindingAttr

A bitmask comprised of one or more BindingFlags that specify how the search is conducted.

-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.

Return Value:
An array of EventInfo objects representing all events which are declared or inherited by the current Type that match the specified binding constraints.

-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.
Remarks
The following BindingFlags filter flags can be used to define which events 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.

Example
         // 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());
         }

    
.NET Framework Security:
ReflectionPermission for reflecting non-public objects. Associated enumeration: ReflectionPermissionFlag.TypeInformation
See also:
EventInfo | BindingFlags | Type.DefaultBinder | ReflectionPermission | Type.GetEvent

Return to top


Overloaded Method: GetField(
   string name
)
Summary
Searches for the field with the specified name.
C# Syntax:
public FieldInfo GetField(
   string name
);
Parameters:

name

The String containing the name of the data field to get.

Return Value:
A FieldInfo object representing the field with the specified name, if found; otherwise, null.
Exceptions
Exception Type Condition
ArgumentNullException name is null.
Remarks
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.

Example
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);
		}
	}
}

    
.NET Framework Security:
ReflectionPermission for reflecting non-public objects. Associated enumeration: ReflectionPermissionFlag.TypeInformation
See also:
FieldInfo | String | Type.DefaultBinder | ReflectionPermission | Type.GetFields

Return to top


Overloaded Method: GetField(
   string name,
   BindingFlags bindingAttr
)
Summary
Searches for the specified field, using the specified binding constraints.
C# Syntax:
public abstract FieldInfo GetField(
   string name,
   BindingFlags bindingAttr
);
Parameters:

name

The String containing the name of the data field to get.

bindingAttr

A bitmask comprised of one or more BindingFlags that specify how the search is conducted.

-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.

Return Value:
A FieldInfo object representing the field that matches the specified requirements, if found; otherwise, null.
Exceptions
Exception Type Condition
ArgumentNullException name is null.
Implements:
IReflect.GetField
Remarks
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.
  1. Hide-by-name-and-signature considers all of the parts of the signature, including custom modifiers, return types, parameter types, sentinels, and unmanaged calling conventions. This is a binary comparison.
  2. For reflection, properties and events are hide-by-name-and-signature. If you have a property with both a get and a set accessor in the base class, but the derived class has only a get accessor, the derived class property hides the base class property, and you will not be able to access the setter on the base class.
  3. Custom attributes are not part of the common type system.

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.

Example
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);
		}
	}
}

    
.NET Framework Security:
ReflectionPermission for reflecting non-public objects. Associated enumeration: ReflectionPermissionFlag.TypeInformation
See also:
FieldInfo | String | BindingFlags | Type.DefaultBinder | ReflectionPermission | Type.GetFields

Return to top


Overloaded Method: GetFields()
Summary
Returns all the public fields of the current Type.
C# Syntax:
public FieldInfo[] GetFields();
Return Value:
An array of FieldInfo objects representing all the public fields defined for the current Type.

-or-

An empty array of type FieldInfo, if no public fields are defined for the current Type.

Remarks
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.
  1. Hide-by-name-and-signature considers all of the parts of the signature, including custom modifiers, return types, parameter types, sentinels, and unmanaged calling conventions. This is a binary comparison.
  2. For reflection, properties and events are hide-by-name-and-signature. If you have a property with both a get and a set accessor in the base class, but the derived class has only a get accessor, the derived class property hides the base class property, and you will not be able to access the setter on the base class.
  3. Custom attributes are not part of the common type system.
Example
			Console.WriteLine("HashCode of the System.Windows.Forms.Button type is  : {0}",
            typeof(System.Windows.Forms.Button).GetHashCode());

    
See also:
FieldInfo | Type.GetField

Return to top


Overloaded Method: GetFields(
   BindingFlags bindingAttr
)
Summary
When overridden in a derived class, searches for the fields defined for the current Type, using the specified binding constraints.
C# Syntax:
public abstract FieldInfo[] GetFields(
   BindingFlags bindingAttr
);
Parameters:

bindingAttr

A bitmask comprised of one or more BindingFlags that specify how the search is conducted.

-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.

Return Value:
An array of FieldInfo objects representing all fields defined for the current Type that match the specified binding constraints.

-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.

Implements:
IReflect.GetFields
Remarks
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.

Example
			Console.WriteLine("HashCode of the System.Windows.Forms.Button type is  : {0}",
            typeof(System.Windows.Forms.Button).GetHashCode());

    
.NET Framework Security:
ReflectionPermission for reflecting non-public objects. Associated enumeration: ReflectionPermissionFlag.TypeInformation
See also:
FieldInfo | BindingFlags | Type.DefaultBinder | ReflectionPermission | Type.GetField

Return to top


Overridden Method: GetHashCode()
Summary
Returns the hash code for this instance.
C# Syntax:
public override int GetHashCode();
Return Value:
An Int32 containing the hash code for this instance.
Remarks
This method overrides Object.GetHashCode.
Example
			Console.WriteLine("HashCode of the System.Windows.Forms.Button type is  : {0}",
            typeof(System.Windows.Forms.Button).GetHashCode());

    

Return to top


Overloaded Method: GetInterface(
   string name
)
Summary
Searches for the interface with the specified name.
C# Syntax:
public Type GetInterface(
   string name
);
Parameters:

name

The String containing the name of the interface to get.

Return Value:
A Type object representing the interface with the specified name, implemented or inherited by the current Type, if found; otherwise, null.
Exceptions
Exception Type Condition
ArgumentNullException name is null.
TargetInvocationException A static initializer is invoked and throws an exception.
Remarks
The search for name is case-sensitive.
Example
    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());            
        }                 
    }

    
See also:
String | Type.GetInterfaces | Type.FindInterfaces

Return to top


Overloaded Method: GetInterface(
   string name,
   bool ignoreCase
)
Summary
When overridden in a derived class, searches for the specified interface, specifying whether to do a case-sensitive search.
C# Syntax:
public abstract Type GetInterface(
   string name,
   bool ignoreCase
);
Parameters:

name

The String containing the name of the interface to get.

ignoreCase

true to perform a case-insensitive search for name.

-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.

Return Value:
A Type object representing the interface with the specified name, implemented or inherited by the current Type, if found; otherwise, null.
Exceptions
Exception Type Condition
ArgumentNullException name is null.
TargetInvocationException A static initializer is invoked and throws an exception.
Remarks
Arrays or COM types are not searched for unless they have been previously loaded into the table of available classes.
Example
    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());            
        }                 
    }

    
See also:
String | Type.GetInterfaces | Type.FindInterfaces

Return to top


Method: GetInterfaceMap(
   Type interfaceType
)
Summary
Returns an interface mapping for the specified interface type.
C# Syntax:
public virtual InterfaceMapping GetInterfaceMap(
   Type interfaceType
);
Parameters:

interfaceType

The Type of the interface of which to retrieve a mapping.

Return Value:
An InterfaceMapping object representing the interface mapping for interfaceType.
Exceptions
Exception Type Condition
ArgumentException The interfaceType parameter does not refer to an interface.
ArgumentNullException interfaceType is null.
Remarks
The interface map denotes how an interface is mapped into the actual methods on a class that implements that interface.
See also:
InterfaceMapping

Return to top


Method: GetInterfaces()
Summary
When overridden in a derived class, gets all the interfaces implemented or inherited by the current Type.
C# Syntax:
public abstract Type[] GetInterfaces();
Return Value:
An array of Type objects representing all the interfaces implemented or inherited by the current Type.

-or-

An empty array of type Type, if no interfaces are implemented or inherited by the current Type.

Exceptions
Exception Type Condition
TargetInvocationException A static initializer is invoked and throws an exception.
Remarks
	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);
			}
		}
	}

    
See also:
Type.GetInterface | Type.FindInterfaces

Return to top


Overloaded Method: GetMember(
   string name
)
Summary
Searches for the members with the specified name.
C# Syntax:
public MemberInfo[] GetMember(
   string name
);
Parameters:

name

The String containing the name of the public members to get.

Return Value:
An array of MemberInfo objects representing the public members with the specified name, if found; otherwise, null.
Exceptions
Exception Type Condition
ArgumentNullException name is null.
Remarks
The search for name is case-sensitive.

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.
  1. Hide-by-name-and-signature considers all of the parts of the signature, including custom modifiers, return types, parameter types, sentinels, and unmanaged calling conventions. This is a binary comparison.
  2. For reflection, properties and events are hide-by-name-and-signature. If you have a property with both a get and a set accessor in the base class, but the derived class has only a get accessor, the derived class property hides the base class property, and you will not be able to access the setter on the base class.
  3. Custom attributes are not part of the common type system.
Example
	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.");    
	}

    
.NET Framework Security:
ReflectionPermission for reflecting non-public objects. Associated enumeration: ReflectionPermissionFlag.TypeInformation
See also:
MemberInfo | String | Type.DefaultBinder | ReflectionPermission | Type.GetMembers | Type.GetDefaultMembers | Type.FindMembers

Return to top


Overloaded Method: GetMember(
   string name,
   BindingFlags bindingAttr
)
Summary
Searches for the specified members, using the specified binding constraints.
C# Syntax:
public virtual MemberInfo[] GetMember(
   string name,
   BindingFlags bindingAttr
);
Parameters:

name

The String containing the name of the members to get.

bindingAttr

A bitmask comprised of one or more BindingFlags that specify how the search is conducted.

-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.

Return Value:
An array of MemberInfo objects representing the public members with the specified name, if found; otherwise, null.
Exceptions
Exception Type Condition
ArgumentNullException name is null.
Implements:
IReflect.GetMember
Remarks
This method can be overridden by a derived class.

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.

Example
	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.");    
	}

    
.NET Framework Security:
ReflectionPermission for reflecting non-public objects. Associated enumeration: ReflectionPermissionFlag.TypeInformation
See also:
MemberInfo | String | BindingFlags | Type.DefaultBinder | ReflectionPermission | Type.GetMembers | Type.GetDefaultMembers | Type.FindMembers

Return to top


Overloaded Method: GetMember(
   string name,
   MemberTypes type,
   BindingFlags bindingAttr
)
Summary
Searches for the specified members of the specified member type, using the specified binding constraints.
C# Syntax:
public virtual MemberInfo[] GetMember(
   string name,
   MemberTypes type,
   BindingFlags bindingAttr
);
Parameters:

name

The String containing the name of the members to get.

type

The Type.MemberType to search for.

bindingAttr

A bitmask comprised of one or more BindingFlags that specify how the search is conducted.

-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.

Return Value:
An array of MemberInfo objects representing the public members with the specified name, if found; otherwise, null.
Exceptions
Exception Type Condition
ArgumentNullException name is null.
NotSupportedException A derived class must provide an implementation.
Remarks
Members include properties, methods, fields, events, and so on.

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.

Example
	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.");    
	}

    
.NET Framework Security:
ReflectionPermission for reflecting non-public objects. Associated enumeration: ReflectionPermissionFlag.TypeInformation
See also:
MemberInfo | String | BindingFlags | Type.DefaultBinder | ReflectionPermission | Type.GetMembers | Type.GetDefaultMembers | Type.FindMembers

Return to top


Overloaded Method: GetMembers()
Summary
Returns all the public members of the current Type.
C# Syntax:
public MemberInfo[] GetMembers();
Return Value:
An array of MemberInfo objects representing all the public members of the current Type.

-or-

An empty array of type MemberInfo, if the current Type does not have public members.

Remarks
Members include properties, methods, fields, events, and so on.

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.
  1. Hide-by-name-and-signature considers all of the parts of the signature, including custom modifiers, return types, parameter types, sentinels, and unmanaged calling conventions. This is a binary comparison.
  2. For reflection, properties and events are hide-by-name-and-signature. If you have a property with both a get and a set accessor in the base class, but the derived class has only a get accessor, the derived class property hides the base class property, and you will not be able to access the setter on the base class.
  3. Custom attributes are not part of the common type system.
Example
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 ); 
      }
   }
}

    
See also:
MemberInfo | Type.GetMember | Type.GetDefaultMembers | Type.FindMembers

Return to top


Overloaded Method: GetMembers(
   BindingFlags bindingAttr
)
Summary
When overridden in a derived class, searches for the members defined for the current Type, using the specified binding constraints.
C# Syntax:
public abstract MemberInfo[] GetMembers(
   BindingFlags bindingAttr
);
Parameters:

bindingAttr

A bitmask comprised of one or more BindingFlags that specify how the search is conducted.

-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.

Return Value:
An array of MemberInfo objects representing all members defined for the current Type that match the specified binding constraints.

-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.

Implements:
IReflect.GetMembers
Remarks
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:

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.

Example

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 ); 
      }      
   }
}


    
.NET Framework Security:
ReflectionPermission for reflecting non-public objects. Associated enumeration: ReflectionPermissionFlag.TypeInformation
See also:
MemberInfo | BindingFlags | Type.DefaultBinder | ReflectionPermission | Type.GetMember | Type.GetDefaultMembers | Type.FindMembers

Return to top


Overloaded Method: GetMethod(
   string name
)
Summary
Searches for the public method with the specified name.
C# Syntax:
public MethodInfo GetMethod(
   string name
);
Parameters:

name

The String containing the name of the public method to get.

Return Value:
A MethodInfo object representing the public method with the specified name, if found; otherwise, null.
Exceptions
Exception Type Condition
AmbiguousMatchException More than one method is found with the specified name.
ArgumentNullException name is null.
Remarks
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.



Note You cannot omit parameters when looking up constructors and methods. You can only omit parameters when invoking.
Example
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 ); 
      }      
   }
}

    
.NET Framework Security:
ReflectionPermission for reflecting non-public objects. Associated enumeration: ReflectionPermissionFlag.TypeInformation
See also:
MethodInfo | String | Type.DefaultBinder | ReflectionPermission | Type.GetMethodImpl | Type.GetMethods

Return to top


Overloaded Method: GetMethod(
   string name,
   BindingFlags bindingAttr
)
Summary
Searches for the specified method, using the specified binding constraints.
C# Syntax:
public MethodInfo GetMethod(
   string name,
   BindingFlags bindingAttr
);
Parameters:

name

The String containing the name of the method to get.

bindingAttr

A bitmask comprised of one or more BindingFlags that specify how the search is conducted.

-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.

Return Value:
A MethodInfo object representing the method that matches the specified requirements, if found; otherwise, null.
Exceptions
Exception Type Condition
AmbiguousMatchException More than one method is found with the specified name and matching the specified binding constraints.
ArgumentNullException name is null.
Implements:
IReflect.GetMethod
Remarks
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.



Note You cannot omit parameters when looking up constructors and methods. You can only omit parameters when invoking.
Example
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);
      }
   }
}

    
.NET Framework Security:
ReflectionPermission for reflecting non-public objects. Associated enumeration: ReflectionPermissionFlag.TypeInformation
See also:
MethodInfo | String | BindingFlags | Type.DefaultBinder | ReflectionPermission | Type.GetMethodImpl | Type.GetMethods

Return to top


Overloaded Method: GetMethod(
   string name,
   Type[] types
)
Summary
Searches for the specified public method whose parameters match the specified argument types.
C# Syntax:
public MethodInfo GetMethod(
   string name,
   Type[] types
);
Parameters:

name

The String containing the name of the public method to get.

types

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.

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.

Return Value:
A MethodInfo object representing the public method whose parameters match the specified argument types, if found; otherwise, null.
Exceptions
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.

Remarks
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.



Note You cannot omit parameters when looking up constructors and methods. You can only omit parameters when invoking.
Example
            // 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);

    
.NET Framework Security:
ReflectionPermission for reflecting non-public objects. Associated enumeration: ReflectionPermissionFlag.TypeInformation
See also:
MethodInfo | String | Type.DefaultBinder | ReflectionPermission | Type.GetMethodImpl | Type.GetMethods

Return to top


Overloaded Method: GetMethod(
   string name,
   Type[] types,
   ParameterModifier[] modifiers
)
Summary
Searches for the specified public method whose parameters match the specified argument types and modifiers.
C# Syntax:
public MethodInfo GetMethod(
   string name,
   Type[] types,
   ParameterModifier[] modifiers
);
Parameters:

name

The String containing the name of the public method to get.

types

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.

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

An array of ParameterModifier objects representing the attributes associated with the corresponding element in the types array. The default binder does not process this parameter.

Return Value:
A MethodInfo object representing the public method that matches the specified requirements, if found; otherwise, null.
Exceptions
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.

Remarks
Although the default binder does not process ParameterModifier (the modifiers parameter), you can use the abstract Binder class to write a custom binder that does process modifiers.ParameterModifier is only used when calling through COM interop, and only parameters that are passed by reference are handled.

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.



Note You cannot omit parameters when looking up constructors and methods. You can only omit parameters when invoking.
.NET Framework Security:
ReflectionPermission for reflecting non-public objects. Associated enumeration: ReflectionPermissionFlag.TypeInformation
See also:
MethodInfo | String | Type.DefaultBinder | ParameterModifier | ReflectionPermission | Type.GetMethodImpl | Type.GetMethods

Return to top


Overloaded Method: GetMethod(
   string name,
   BindingFlags bindingAttr,
   Binder binder,
   Type[] types,
   ParameterModifier[] modifiers
)
Summary
Searches for the specified method whose parameters match the specified argument types and modifiers, using the specified binding constraints.
C# Syntax:
public MethodInfo GetMethod(
   string name,
   BindingFlags bindingAttr,
   Binder binder,
   Type[] types,
   ParameterModifier[] modifiers
);
Parameters:

name

The String containing the name of the method to get.

bindingAttr

A bitmask comprised of one or more BindingFlags that specify how the search is conducted.

-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

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.

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

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.

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

An array of ParameterModifier objects representing the attributes associated with the corresponding element in the types array. The default binder does not process this parameter.

Return Value:
A MethodInfo object representing the method that matches the specified requirements, if found; otherwise, null.
Exceptions
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.

Implements:
IReflect.GetMethod
Remarks
Although the default binder does not process ParameterModifier (the modifiers parameter), you can use the abstract Binder class to write a custom binder that does process modifiers.ParameterModifier is only used when calling through COM interop, and only parameters that are passed by reference are handled.

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.



Note You cannot omit parameters when looking up constructors and methods. You can only omit parameters when invoking.
Example
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);
      }
   }
}

    
.NET Framework Security:
ReflectionPermission for reflecting non-public objects. Associated enumeration: ReflectionPermissionFlag.TypeInformation
See also:
MethodInfo | String | BindingFlags | Binder | Type.DefaultBinder | ParameterModifier | ReflectionPermission | Type.GetMethodImpl | Type.GetMethods

Return to top


Overloaded Method: GetMethod(
   string name,
   BindingFlags bindingAttr,
   Binder binder,
   CallingConventions callConvention,
   Type[] types,
   ParameterModifier[] modifiers
)
Summary
Searches for the specified method whose parameters match the specified argument types and modifiers, using the specified binding constraints and the specified calling convention.
C# Syntax:
public MethodInfo GetMethod(
   string name,
   BindingFlags bindingAttr,
   Binder binder,
   CallingConventions callConvention,
   Type[] types,
   ParameterModifier[] modifiers
);
Parameters:

name

The String containing the name of the method to get.

bindingAttr

A bitmask comprised of one or more BindingFlags that specify how the search is conducted.

-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

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.

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

The CallingConventions object that specifies the set of rules to use regarding the order and layout of arguments, how the return value is passed, what registers are used for arguments, and how the stack is cleaned up.

types

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.

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

An array of ParameterModifier objects representing the attributes associated with the corresponding element in the types array. The default binder does not process this parameter.

Return Value:
A MethodInfo object representing the method that matches the specified requirements, if found; otherwise, null.
Exceptions
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.

Remarks
Although the default binder does not process ParameterModifier (the modifiers parameter), you can use the abstract Binder class to write a custom binder that does process modifiers.ParameterModifier is only used when calling through COM interop, and only parameters that are passed by reference are handled.

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.
  1. Hide-by-name-and-signature considers all of the parts of the signature, including custom modifiers, return types, parameter types, sentinels, and unmanaged calling conventions. This is a binary comparison.
  2. For reflection, properties and events are hide-by-name-and-signature. If you have a property with both a get and a set accessor in the base class, but the derived class has only a get accessor, the derived class property hides the base class property, and you will not be able to access the setter on the base class.
  3. Custom attributes are not part of the common type system.

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.



Note You cannot omit parameters when looking up constructors and methods. You can only omit parameters when invoking.
Example

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);
      }
   }
}

    
.NET Framework Security:
ReflectionPermission for reflecting non-public objects. Associated enumeration: ReflectionPermissionFlag.TypeInformation
See also:
MethodInfo | String | BindingFlags | Binder | Type.DefaultBinder | CallingConventions | ParameterModifier | ReflectionPermission | Type.GetMethodImpl | Type.GetMethods

Return to top


Method: GetMethodImpl(
   string name,
   BindingFlags bindingAttr,
   Binder binder,
   CallingConventions callConvention,
   Type[] types,
   ParameterModifier[] modifiers
)
Summary
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.
C# Syntax:
protected abstract MethodInfo GetMethodImpl(
   string name,
   BindingFlags bindingAttr,
   Binder binder,
   CallingConventions callConvention,
   Type[] types,
   ParameterModifier[] modifiers
);
Parameters:

name

The String containing the name of the method to get.

bindingAttr

A bitmask comprised of one or more BindingFlags that specify how the search is conducted.

-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

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.

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

The CallingConventions object that specifies the set of rules to use regarding the order and layout of arguments, how the return value is passed, what registers are used for arguments, and what process cleans up the stack.

types

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.

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

An array of ParameterModifier objects representing the attributes associated with the corresponding element in the types array. The default binder does not process this parameter.

Return Value:
A MethodInfo object representing the method that matches the specified requirements, if found; otherwise, null.
Exceptions
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.

Remarks
Although the default binder does not process ParameterModifier (the modifiers parameter), you can use the abstract Binder class to write a custom binder that does process modifiers.ParameterModifier is only used when calling through COM interop, and only parameters that are passed by reference are handled.

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.

.NET Framework Security:
ReflectionPermission for reflecting non-public objects. Associated enumeration: ReflectionPermissionFlag.TypeInformation
See also:
MethodInfo | String | BindingFlags | Binder | Type.DefaultBinder | CallingConventions | ParameterModifier | ReflectionPermission | Type.GetMethod | Type.GetMethods

Return to top


Overloaded Method: GetMethods()
Summary
Returns all the public methods of the current Type.
C# Syntax:
public MethodInfo[] GetMethods();
Return Value:
An array of MethodInfo objects representing all the public methods defined for the current Type.

-or-

An empty array of type MethodInfo, if no public methods are defined for the current Type.

Remarks
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.
  1. Hide-by-name-and-signature considers all of the parts of the signature, including custom modifiers, return types, parameter types, sentinels, and unmanaged calling conventions. This is a binary comparison.
  2. For reflection, properties and events are hide-by-name-and-signature. If you have a property with both a get and a set accessor in the base class, but the derived class has only a get accessor, the derived class property hides the base class property, and you will not be able to access the setter on the base class.
  3. Custom attributes are not part of the common type system.


Note You cannot omit parameters when looking up constructors and methods. You can only omit parameters when invoking.
See also:
MethodInfo | Type.GetMethod

Return to top


Overloaded Method: GetMethods(
   BindingFlags bindingAttr
)
Summary
When overridden in a derived class, searches for the methods defined for the current Type, using the specified binding constraints.
C# Syntax:
public abstract MethodInfo[] GetMethods(
   BindingFlags bindingAttr
);
Parameters:

bindingAttr

A bitmask comprised of one or more BindingFlags that specify how the search is conducted.

-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.

Return Value:
An array of MethodInfo objects representing all methods defined for the current Type that match the specified binding constraints.

-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.

Implements:
IReflect.GetMethods
Remarks
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.



Note You cannot omit parameters when looking up constructors and methods. You can only omit parameters when invoking.
Example
			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);
				}
			}

    
.NET Framework Security:
ReflectionPermission for reflecting non-public objects. Associated enumeration: ReflectionPermissionFlag.TypeInformation
See also:
MethodInfo | BindingFlags | Type.DefaultBinder | ReflectionPermission | Type.GetMethod

Return to top


Overloaded Method: GetNestedType(
   string name
)
Summary
Searches for the nested type with the specified name.
C# Syntax:
public Type GetNestedType(
   string name
);
Parameters:

name

The String containing the name of the nested type to get.

Return Value:
A Type object representing the nested type with the specified name, if found; otherwise, null.
Exceptions
Exception Type Condition
ArgumentNullException name is null.
Remarks
The search for name is case-sensitive.

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.
  1. Hide-by-name-and-signature considers all of the parts of the signature, including custom modifiers, return types, parameter types, sentinels, and unmanaged calling conventions. This is a binary comparison.
  2. For reflection, properties and events are hide-by-name-and-signature. If you have a property with both a get and a set accessor in the base class, but the derived class has only a get accessor, the derived class property hides the base class property, and you will not be able to access the setter on the base class.
  3. Custom attributes are not part of the common type system.
See also:
String | Type.DefaultBinder | Type.GetNestedTypes

Return to top


Overloaded Method: GetNestedType(
   string name,
   BindingFlags bindingAttr
)
Summary
When overridden in a derived class, searches for the specified nested type, using the specified binding constraints.
C# Syntax:
public abstract Type GetNestedType(
   string name,
   BindingFlags bindingAttr
);
Parameters:

name

The String containing the name of the nested type to get.

bindingAttr

A bitmask comprised of one or more BindingFlags that specify how the search is conducted.

-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.

Return Value:
A Type object representing the nested type that matches the specified requirements, if found; otherwise, null.
Exceptions
Exception Type Condition
ArgumentNullException name is null.
Remarks
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.

.NET Framework Security:
ReflectionPermission for reflecting methods that are not public. Associated enumerations: ReflectionPermissionFlag.MemberAccess, ReflectionPermissionFlag.TypeInformation
See also:
String | BindingFlags | Type.DefaultBinder | Type.GetNestedTypes

Return to top


Overloaded Method: GetNestedTypes()
Summary
Returns all the types nested within the current Type.
C# Syntax:
public Type[] GetNestedTypes();
Return Value:
An array of Type objects representing all the types nested within the current Type.

-or-

An empty array of type Type, if no types are nested within the current Type.
Remarks
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.
  1. Hide-by-name-and-signature considers all of the parts of the signature, including custom modifiers, return types, parameter types, sentinels, and unmanaged calling conventions. This is a binary comparison.
  2. For reflection, properties and events are hide-by-name-and-signature. If you have a property with both a get and a set accessor in the base class, but the derived class has only a get accessor, the derived class property hides the base class property, and you will not be able to access the setter on the base class.
  3. Custom attributes are not part of the common type system.
Example
                  // 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());

    
See also:
Type.GetNestedType

Return to top


Overloaded Method: GetNestedTypes(
   BindingFlags bindingAttr
)
Summary
When overridden in a derived class, searches for the types nested within the current Type, using the specified binding constraints.
C# Syntax:
public abstract Type[] GetNestedTypes(
   BindingFlags bindingAttr
);
Parameters:

bindingAttr

A bitmask comprised of one or more BindingFlags that specify how the search is conducted.

-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.

Return Value:
An array of Type objects representing all the types nested within the current Type that match the specified binding constraints.

-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.

Remarks
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:

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.

Example
			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());
				}
			}

    
.NET Framework Security:
ReflectionPermission for reflecting methods that are not public. Associated enumerations: ReflectionPermissionFlag.MemberAccess, ReflectionPermissionFlag.TypeInformation
See also:
BindingFlags | Type.DefaultBinder | Type.GetNestedType

Return to top


Overloaded Method: GetProperties()
Summary
Returns all the public properties of the current Type.
C# Syntax:
public PropertyInfo[] GetProperties();
Return Value:
An array of PropertyInfo objects representing all public properties of the current Type.

-or-

An empty array of type PropertyInfo, if the current Type does not have public properties.

Remarks
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.
  1. Hide-by-name-and-signature considers all of the parts of the signature, including custom modifiers, return types, parameter types, sentinels, and unmanaged calling conventions. This is a binary comparison.
  2. For reflection, properties and events are hide-by-name-and-signature. If you have a property with both a get and a set accessor in the base class, but the derived class has only a get accessor, the derived class property hides the base class property, and you will not be able to access the setter on the base class.
  3. Custom attributes are not part of the common type system.
Example
				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());
				}

    
See also:
PropertyInfo | Type.GetProperty

Return to top


Overloaded Method: GetProperties(
   BindingFlags bindingAttr
)
Summary
When overridden in a derived class, searches for the properties of the current Type, using the specified binding constraints.
C# Syntax:
public abstract PropertyInfo[] GetProperties(
   BindingFlags bindingAttr
);
Parameters:

bindingAttr

A bitmask comprised of one or more BindingFlags that specify how the search is conducted.

-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.

Return Value:
An array of PropertyInfo objects representing all properties of the current Type that match the specified binding constraints.

-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.

Implements:
IReflect.GetProperties
Remarks
A property is considered public to reflection if it has at least one accessor that is public. That is, you can call type.GetProperty("propertyname", BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static) to get it.

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.

Example
				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);
					}
				}

    
See also:
PropertyInfo | BindingFlags | Type.DefaultBinder | Type.GetProperty

Return to top


Overloaded Method: GetProperty(
   string name
)
Summary
Searches for the public property with the specified name.
C# Syntax:
public PropertyInfo GetProperty(
   string name
);
Parameters:

name

The String containing the name of the public property to get.

Return Value:
A PropertyInfo object representing the public property with the specified name, if found; otherwise, null.
Exceptions
Exception Type Condition
AmbiguousMatchException More than one property is found with the specified name.
ArgumentNullException name is null.
Remarks
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.

Example
Different languages use different syntax to specify default or parameterized properties.
            // 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.

See also:
PropertyInfo | String | Type.DefaultBinder | ReflectionPermission | Type.GetPropertyImpl | Type.GetProperties

Return to top


Overloaded Method: GetProperty(
   string name,
   BindingFlags bindingAttr
)
Summary
Searches for the specified property, using the specified binding constraints.
C# Syntax:
public PropertyInfo GetProperty(
   string name,
   BindingFlags bindingAttr
);
Parameters:

name

The String containing the name of the property to get.

bindingAttr

A bitmask comprised of one or more BindingFlags that specify how the search is conducted.

-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.

Return Value:
A PropertyInfo object representing the property that matches the specified requirements, if found; otherwise, null.
Exceptions
Exception Type Condition
AmbiguousMatchException More than one property is found with the specified name and matching the specified binding constraints.
ArgumentNullException name is null.
Implements:
IReflect.GetProperty
Remarks
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.

Example
Different languages use different syntax to specify default or parameterized properties.
            // 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.

See also:
PropertyInfo | String | BindingFlags | Type.DefaultBinder | ReflectionPermission | Type.GetPropertyImpl | Type.GetProperties

Return to top


Overloaded Method: GetProperty(
   string name,
   Type returnType
)
Summary
Searches for the public property with the specified name and return type.
C# Syntax:
public PropertyInfo GetProperty(
   string name,
   Type returnType
);
Parameters:

name

The String containing the name of the public property to get.

returnType

The return type of the property.

Return Value:
A PropertyInfo object representing the public property with the specified name, if found; otherwise, null.
Exceptions
Exception Type Condition
AmbiguousMatchException More than one property is found with the specified name.
ArgumentNullException name is null.
Remarks
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.

Example
Different languages use different syntax to specify default or parameterized properties.
			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.

See also:
PropertyInfo | String | Type.DefaultBinder | ReflectionPermission | Type.GetPropertyImpl | Type.GetProperties

Return to top


Overloaded Method: GetProperty(
   string name,
   Type[] types
)
Summary
Searches for the specified public property whose parameters match the specified argument types.
C# Syntax:
public PropertyInfo GetProperty(
   string name,
   Type[] types
);
Parameters:

name

The String containing the name of the public property to get.

types

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.

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.

Return Value:
A PropertyInfo object representing the public property whose parameters match the specified argument types, if found; otherwise, null.
Exceptions
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.
Remarks
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.

Example
Different languages use different syntax to specify default or parameterized properties.
				// 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.

See also:
PropertyInfo | String | Type.DefaultBinder | ReflectionPermission | Type.GetPropertyImpl | Type.GetProperties

Return to top


Overloaded Method: GetProperty(
   string name,
   Type returnType,
   Type[] types
)
Summary
Searches for the specified public property whose parameters match the specified argument types.
C# Syntax:
public PropertyInfo GetProperty(
   string name,
   Type returnType,
   Type[] types
);
Parameters:

name

The String containing the name of the public property to get.

returnType

The return type of the property.

types

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.

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.

Return Value:
A PropertyInfo object representing the public property whose parameters match the specified argument types, if found; otherwise, null.
Exceptions
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.
Remarks
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.

Example
See also:
PropertyInfo | String | Type.DefaultBinder | ReflectionPermission | Type.GetPropertyImpl | Type.GetProperties

Return to top


Overloaded Method: GetProperty(
   string name,
   Type returnType,
   Type[] types,
   ParameterModifier[] modifiers
)
Summary
Searches for the specified public property whose parameters match the specified argument types and modifiers.
C# Syntax:
public PropertyInfo GetProperty(
   string name,
   Type returnType,
   Type[] types,
   ParameterModifier[] modifiers
);
Parameters:

name

The String containing the name of the public property to get.

returnType

The return type of the property.

types

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.

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

An array of ParameterModifier objects representing the attributes associated with the corresponding element in the types array. The default binder does not process this parameter.

Return Value:
A PropertyInfo object representing the public property that matches the specified requirements, if found; otherwise, null.
Exceptions
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.

Remarks
Although the default binder does not process ParameterModifier (the modifiers parameter), you can use the abstract Binder class to write a custom binder that does process modifiers.ParameterModifier is only used when calling through COM interop, and only parameters that are passed by reference are handled.

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.

Example
Different languages use different syntax to specify default or parameterized properties.
// 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.

See also:
PropertyInfo | String | Type.DefaultBinder | ParameterModifier | ReflectionPermission | Type.GetPropertyImpl | Type.GetProperties

Return to top


Overloaded Method: GetProperty(
   string name,
   BindingFlags bindingAttr,
   Binder binder,
   Type returnType,
   Type[] types,
   ParameterModifier[] modifiers
)
Summary
Searches for the specified property whose parameters match the specified argument types and modifiers, using the specified binding constraints.
C# Syntax:
public PropertyInfo GetProperty(
   string name,
   BindingFlags bindingAttr,
   Binder binder,
   Type returnType,
   Type[] types,
   ParameterModifier[] modifiers
);
Parameters:

name

The String containing the name of the property to get.

bindingAttr

A bitmask comprised of one or more BindingFlags that specify how the search is conducted.

-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

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.

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

The return type of the property.

types

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.

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

An array of ParameterModifier objects representing the attributes associated with the corresponding element in the types array. The default binder does not process this parameter.

Return Value:
A PropertyInfo object representing the property that matches the specified requirements, if found; otherwise, null.
Exceptions
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.

Implements:
IReflect.GetProperty
Remarks
Although the default binder does not process ParameterModifier (the modifiers parameter), you can use the abstract Binder class to write a custom binder that does process modifiers.ParameterModifier is only used when calling through COM interop, and only parameters that are passed by reference are handled.

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.
  1. Hide-by-name-and-signature considers all of the parts of the signature, including custom modifiers, return types, parameter types, sentinels, and unmanaged calling conventions. This is a binary comparison.
  2. For reflection, properties and events are hide-by-name-and-signature. If you have a property with both a get and a set accessor in the base class, but the derived class has only a get accessor, the derived class property hides the base class property, and you will not be able to access the setter on the base class.
  3. Custom attributes are not part of the common type system.

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.

Example
Different languages use different syntax to specify default or parameterized properties.

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.

See also:
PropertyInfo | String | BindingFlags | Binder | Type.DefaultBinder | ParameterModifier | ReflectionPermission | Type.GetPropertyImpl | Type.GetProperties

Return to top


Method: GetPropertyImpl(
   string name,
   BindingFlags bindingAttr,
   Binder binder,
   Type returnType,
   Type[] types,
   ParameterModifier[] modifiers
)
Summary
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.
C# Syntax:
protected abstract PropertyInfo GetPropertyImpl(
   string name,
   BindingFlags bindingAttr,
   Binder binder,
   Type returnType,
   Type[] types,
   ParameterModifier[] modifiers
);
Parameters:

name

The String containing the name of the property to get.

bindingAttr

A bitmask comprised of one or more BindingFlags that specify how the search is conducted.

-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

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.

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

The return type of the property.

types

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.

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

An array of ParameterModifier objects representing the attributes associated with the corresponding element in the types array. The default binder does not process this parameter.

Return Value:
A PropertyInfo object representing the property that matches the specified requirements, if found; otherwise, null.
Exceptions
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.

Remarks
Although the default binder does not process ParameterModifier (the modifiers parameter), you can use the abstract Binder class to write a custom binder that does process modifiers.ParameterModifier is only used when calling through COM interop, and only parameters that are passed by reference are handled.

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.

See also:
PropertyInfo | String | BindingFlags | Binder | Type.DefaultBinder | ParameterModifier | ReflectionPermission | Type.GetProperty | Type.GetProperties

Return to top


Overloaded Method: GetType()
Inherited
See base class member description: System.Object.GetType
C# Syntax:
public Type GetType();

For more information on members inherited from System.Object click on the link above.

Return to top


Overloaded Method: GetType(
   string typeName
)
Summary
Gets the Type with the specified name, performing a case-sensitive search.
C# Syntax:
public static Type GetType(
   string typeName
);
Parameters:

typeName

The name of the Type to get.

Return Value:
The Type with the specified name, if found; otherwise, null.
Exceptions
Exception Type Condition
ArgumentNullException typeName is null.
TargetInvocationException A class initializer is invoked and throws an exception.
Remarks
GetType only works on assemblies loaded from disk. If you call GetType to look up a type defined in a dynamic assembly defined using the System.Reflection.Emit services, you might get inconsistent behavior. The behavior depends on whether the dynamic assembly is persistent, that is, created using the RunAndSave or Save access modes of the AssemblyBuilderAccess enumeration. If the dynamic assembly is persistent and has been written to disk before GetType is called, the loader finds the saved assembly on disk, loads that assembly, and retrieves the type from that assembly. If the assembly has not been saved to disk when GetType is called, the method returns null.GetType does not understand transient dynamic assemblies; therefore, calling GetType to retrieve a type in a transient dynamic assembly returns null.

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.
  1. Hide-by-name-and-signature considers all of the parts of the signature, including custom modifiers, return types, parameter types, sentinels, and unmanaged calling conventions. This is a binary comparison.
  2. For reflection, properties and events are hide-by-name-and-signature. If you have a property with both a get and a set accessor in the base class, but the derived class has only a get accessor, the derived class property hides the base class property, and you will not be able to access the setter on the base class.
  3. Custom attributes are not part of the common type system.

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[,]")
Example
			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);
			}

    
.NET Framework Security:
ReflectionPermission for reflecting non-public objects. Associated enumeration: ReflectionPermissionFlag.TypeInformation
See also:
String | TypeLoadException | ReflectionPermission | Type.AssemblyQualifiedName | Assembly.GetAssembly | Assembly.GetType | AssemblyName | MSDN: specifyingfullyqualifiedtypenames

Return to top


Overloaded Method: GetType(
   string typeName,
   bool throwOnError
)
Summary
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.
C# Syntax:
public static Type GetType(
   string typeName,
   bool throwOnError
);
Parameters:

typeName

The name of the Type to get.

throwOnError

true to throw a TypeLoadException if an error occurs while loading the Type.

-or-

false to ignore errors while loading the Type.

true to throw a TypeLoadException if an error occurs while loading the Type.

-or-

false to ignore errors while loading the Type.

Return Value:
The Type with the specified name, if found; otherwise, null.
Exceptions
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.
Remarks
GetType only works on assemblies loaded from disk. If you call GetType to look up a type defined in a dynamic assembly defined using the System.Reflection.Emit services, you might get inconsistent behavior. The behavior depends on whether the dynamic assembly is persistent, that is, created using the RunAndSave or Save access modes of the AssemblyBuilderAccess enumeration. If the dynamic assembly is persistent and has been written to disk before GetType is called, the loader finds the saved assembly on disk, loads that assembly, and retrieves the type from that assembly. If the assembly has not been saved to disk when GetType is called, the method returns null.GetType does not understand transient dynamic assemblies; therefore, calling GetType to retrieve a type in a transient dynamic assembly returns null.

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.
  1. Hide-by-name-and-signature considers all of the parts of the signature, including custom modifiers, return types, parameter types, sentinels, and unmanaged calling conventions. This is a binary comparison.
  2. For reflection, properties and events are hide-by-name-and-signature. If you have a property with both a get and a set accessor in the base class, but the derived class has only a get accessor, the derived class property hides the base class property, and you will not be able to access the setter on the base class.
  3. Custom attributes are not part of the common type system.

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[,]")
Example
			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);
			}

    
.NET Framework Security:
ReflectionPermission for reflecting non-public objects. Associated enumeration: ReflectionPermissionFlag.TypeInformation
See also:
String | TypeLoadException | ReflectionPermission | Type.AssemblyQualifiedName | Assembly.GetAssembly | Assembly.GetType | AssemblyName | MSDN: specifyingfullyqualifiedtypenames

Return to top


Overloaded Method: GetType(
   string typeName,
   bool throwOnError,
   bool ignoreCase
)
Summary
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.
C# Syntax:
public static Type GetType(
   string typeName,
   bool throwOnError,
   bool ignoreCase
);
Parameters:

typeName

The name of the Type to get.

throwOnError

true to throw a TypeLoadException if an error occurs while loading the Type.

-or-

false to ignore errors while loading the Type.

true to throw a TypeLoadException if an error occurs while loading the Type.

-or-

false to ignore errors while loading the Type.

ignoreCase

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.

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.

Return Value:
The Type with the specified name, if found; otherwise, null.
Exceptions
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.
Remarks
GetType only works on assemblies loaded from disk. If you call GetType to look up a type defined in a dynamic assembly defined using the System.Reflection.Emit services, you might get inconsistent behavior. The behavior depends on whether the dynamic assembly is persistent, that is, created using the RunAndSave or Save access modes of the AssemblyBuilderAccess enumeration. If the dynamic assembly is persistent and has been written to disk before GetType is called, the loader finds the saved assembly on disk, loads that assembly, and retrieves the type from that assembly. If the assembly has not been saved to disk when GetType is called, the method returns null.GetType does not understand transient dynamic assemblies; therefore, calling GetType to retrieve a type in a transient dynamic assembly returns null.

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.
  1. Hide-by-name-and-signature considers all of the parts of the signature, including custom modifiers, return types, parameter types, sentinels, and unmanaged calling conventions. This is a binary comparison.
  2. For reflection, properties and events are hide-by-name-and-signature. If you have a property with both a get and a set accessor in the base class, but the derived class has only a get accessor, the derived class property hides the base class property, and you will not be able to access the setter on the base class.
  3. Custom attributes are not part of the common type system.

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[,]")
.NET Framework Security:
ReflectionPermission for reflecting non-public objects. Associated enumeration: ReflectionPermissionFlag.TypeInformation
See also:
String | TypeLoadException | ReflectionPermission | Type.AssemblyQualifiedName | Assembly.GetAssembly | Assembly.GetType | AssemblyName | MSDN: specifyingfullyqualifiedtypenames

Return to top


Method: GetTypeArray(
   object[] args
)
Summary
Gets the types of the objects in the specified array.
C# Syntax:
public static Type[] GetTypeArray(
   object[] args
);
Parameters:

args

An array of objects whose types to determine.

Return Value:
An array of Type objects representing the types of the corresponding elements in args.
Exceptions
Exception Type Condition
ArgumentNullException args is null.
TargetInvocationException The class initializers are invoked and at least one throws an exception.
Remarks
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.
Example
				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);
				}

    
See also:
ReflectionPermission

Return to top


Method: GetTypeCode(
   Type type
)
Summary
Gets the underlying type code of the specified Type.
C# Syntax:
public static TypeCode GetTypeCode(
   Type type
);
Parameters:

type

The Type whose underlying type code to get.

Return Value:
The TypeCode value of the underlying type.
Example
				// 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);

    
See also:
TypeCode

Return to top


Method: GetTypeFromHandle(
   RuntimeTypeHandle handle
)
Summary
Gets the Type referenced by the specified type handle.
C# Syntax:
public static Type GetTypeFromHandle(
   RuntimeTypeHandle handle
);
Parameters:

handle

The RuntimeTypeHandle object that refers to the Type.

Return Value:
The Type referenced by the specified RuntimeTypeHandle.
Exceptions
Exception Type Condition
ArgumentNullException handle is null.
TargetInvocationException A class initializer is invoked and throws an exception.
Remarks
The handles are valid only in the application domain in which they were obtained.

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.

Example
        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);

    
.NET Framework Security:
ReflectionPermission for reflecting non-public objects. Associated enumeration: ReflectionPermissionFlag.TypeInformation
See also:
RuntimeTypeHandle | Type.TypeHandle | Type.GetTypeHandle | ReflectionPermission

Return to top


Method: GetTypeHandle(
   object o
)
Summary
Gets the handle for the Type of a specified object.
C# Syntax:
public static RuntimeTypeHandle GetTypeHandle(
   object o
);
Parameters:

o

The Object for which to get the Type handle.

Return Value:
The handle for the Type of the specified Object.
Remarks
The handles are valid only in the application domain in which they were obtained.
Example
       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());

    
See also:
RuntimeTypeHandle | Type.TypeHandle | Type.GetTypeFromHandle

Return to top


Method: HasElementTypeImpl()
Summary
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.
C# Syntax:
protected abstract bool HasElementTypeImpl();
Return Value:
true if the Type is an array, a pointer, or is passed by reference; otherwise, false.
Remarks
For example, Type.GetType("Int32[]").HasElementTypeImpl returns true, but Type.GetType("Int32").HasElementTypeImpl returns false. HasElementTypeImpl also returns true for "Int32*" and "Int32&".
Example
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);
      }
   }
}

    
See also:
Type.HasElementType | Type.IsArray | Type.IsPointer | Type.IsByRef | Type.GetElementType | Type.GetType

Return to top


Overloaded Method: InvokeMember(
   string name,
   BindingFlags invokeAttr,
   Binder binder,
   object target,
   object[] args
)
Summary
Invokes the specified member, using the specified binding constraints and matching the specified argument list.
C# Syntax:
public object InvokeMember(
   string name,
   BindingFlags invokeAttr,
   Binder binder,
   object target,
   object[] args
);
Parameters:

name

The String containing the name of the constructor, method, property, or field member to invoke. -or-

An empty string ("") to invoke the default member.

-or-

An empty string ("") to invoke the default member.

invokeAttr

A bitmask comprised of one or more BindingFlags that specify how the search is conducted. The access can be one of the BindingFlags such as Public, NonPublic, Private, InvokeMethod, GetField, and so on. The type of lookup need not be specified. If the type of lookup is omitted, BindingFlags.Public | BindingFlags.Instance will apply.

binder

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.

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

The Object on which to invoke the specified member.

args

An array containing the arguments to pass to the member to invoke.

Return Value:
An Object representing the return value of the invoked member.
Exceptions
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.
Remarks
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:

The binder will find all of the matching methods. These methods are found based upon the type of binding requested ( BindingFlags values InvokeMethod, GetProperty, and so on). The set of methods is filtered by the name, number of arguments, and a set of search modifiers defined in the binder.

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".

Example
Here are syntax examples using InvokeMember to invoke, get, and set various members.
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 {}

    
.NET Framework Security:
ReflectionPermission for reflecting members that are not public. Associated enumeration: ReflectionPermissionFlag.MemberAccess
.NET Framework Security:
SecurityPermission to call unmanaged code. Associated enumeration: SecurityPermissionFlag.UnmanagedCode
See also:
String | Binder | Type.DefaultBinder | BindingFlags | ParameterModifier | ParameterAttributes | CultureInfo | ReflectionPermission

Return to top


Overloaded Method: InvokeMember(
   string name,
   BindingFlags invokeAttr,
   Binder binder,
   object target,
   object[] args,
   CultureInfo culture
)
Summary
Invokes the specified member, using the specified binding constraints and matching the specified argument list and culture.
C# Syntax:
public object InvokeMember(
   string name,
   BindingFlags invokeAttr,
   Binder binder,
   object target,
   object[] args,
   CultureInfo culture
);
Parameters:

name

The String containing the name of the constructor, method, property, or field member to invoke.

-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

A bitmask comprised of one or more BindingFlags that specify how the search is conducted. The access can be one of the BindingFlags such as Public, NonPublic, Private, InvokeMethod, GetField, and so on. The type of lookup need not be specified. If the type of lookup is omitted, BindingFlags.Public | BindingFlags.Instance will apply.

binder

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.

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

The Object on which to invoke the specified member.

args

An array containing the arguments to pass to the member to invoke.

culture

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.

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.

Return Value:
An Object representing the return value of the invoked member.
Exceptions
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.
Remarks
Although the default binder does not process CultureInfo (the culture parameter), you can use the abstract Binder class to write a custom binder that does process culture.

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:

The binder will find all of the matching methods. These methods are found based upon the type of binding requested ( BindingFlags values InvokeMethod, GetProperty, and so on). The set of methods is filtered by the name, number of arguments, and a set of search modifiers defined in the binder.

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".

Example
Here are syntax examples using InvokeMember to invoke, get, and set various members.
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 {}

    
.NET Framework Security:
ReflectionPermission for reflecting members that are not public. Associated enumeration: ReflectionPermissionFlag.MemberAccess
.NET Framework Security:
SecurityPermission to call unmanaged code. Associated enumeration: SecurityPermissionFlag.UnmanagedCode
See also:
String | Binder | Type.DefaultBinder | BindingFlags | ParameterModifier | ParameterAttributes | CultureInfo | ReflectionPermission

Return to top


Overloaded Method: InvokeMember(
   string name,
   BindingFlags invokeAttr,
   Binder binder,
   object target,
   object[] args,
   ParameterModifier[] modifiers,
   CultureInfo culture,
   string[] namedParameters
)
Summary
When overridden in a derived class, invokes the specified member, using the specified binding constraints and matching the specified argument list, modifiers and culture.
C# Syntax:
public abstract object InvokeMember(
   string name,
   BindingFlags invokeAttr,
   Binder binder,
   object target,
   object[] args,
   ParameterModifier[] modifiers,
   CultureInfo culture,
   string[] namedParameters
);
Parameters:

name

The String containing the name of the constructor, method, property, or field member to invoke.

-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

A bitmask comprised of one or more BindingFlags that specify how the search is conducted. The access can be one of the BindingFlags such as Public, NonPublic, Private, InvokeMethod, GetField, and so on. The type of lookup need not be specified. If the type of lookup is omitted, BindingFlags.Public | BindingFlags.Instance will apply.

binder

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.

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

The Object on which to invoke the specified member.

args

An array containing the arguments to pass to the member to invoke.

modifiers

An array of ParameterModifier objects representing the attributes associated with the corresponding element in the args array. A parameter's associated attributes are stored in the member's signature. The default binder does not process this parameter. An array of ParameterModifier objects representing the attributes associated with the corresponding element in the args array. A parameter's associated attributes are stored in the member's signature. The default binder does not process this parameter.

culture

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.

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

An array containing the names of the parameters to which the values in the args array are passed.

Return Value:
An Object representing the return value of the invoked member.
Exceptions
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.
Implements:
IReflect.InvokeMember
Remarks
InvokeMember calls a constructor member or a method member, gets or sets a property member, gets or sets a data field member, or gets or sets an element of an array member.

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:

The binder will find all of the matching methods. These methods are found based upon the type of binding requested ( BindingFlags values InvokeMethod, GetProperty, and so on). The set of methods is filtered by the name, number of arguments, and a set of search modifiers defined in the binder.

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".

Example
Here are syntax examples using InvokeMember to invoke, get, and set various members.
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 {}

    
.NET Framework Security:
ReflectionPermission for reflecting members that are not public. Associated enumeration: ReflectionPermissionFlag.MemberAccess
.NET Framework Security:
SecurityPermission to call unmanaged code. Associated enumeration: SecurityPermissionFlag.UnmanagedCode
See also:
String | Binder | Type.DefaultBinder | BindingFlags | ParameterModifier | ParameterAttributes | CultureInfo | ReflectionPermission

Return to top


Method: IsArrayImpl()
Summary
When overridden in a derived class, implements the Type.IsArray property and determines whether the Type is an array.
C# Syntax:
protected abstract bool IsArrayImpl();
Return Value:
true if the Type is an array; otherwise, false.
Remarks
An instance of the Array class must return false because it is an object, not an array.
Example
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 );
      }
   }
}

    
See also:
Type.IsArray

Return to top


Method: IsAssignableFrom(
   Type c
)
Summary
Determines whether an instance of the current Type can be assigned from an instance of the specified Type.
C# Syntax:
public virtual bool IsAssignableFrom(
   Type c
);
Parameters:

c

The Type to compare with the current Type.

Return Value:
true if the c parameter and the current Type represent the same type, or if the current Type is in the inheritance hierarchy of c, or if the current Type is an interface that c supports.false if none of these conditions are the case, or if c is null.
Remarks
This method can be overridden by a derived class.

Determine the element types of a Type using Type.GetElementType.

Example
The following example demonstrates the IsAssignable method using arrays.
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
              			
            

Return to top


Method: IsByRefImpl()
Summary
When overridden in a derived class, implements the Type.IsByRef property and determines whether the Type is passed by reference.
C# Syntax:
protected abstract bool IsByRefImpl();
Return Value:
true if the Type is passed by reference; otherwise, false.
Remarks
See also:
Type.IsByRef

Return to top


Method: IsCOMObjectImpl()
Summary
When overridden in a derived class, implements the Type.IsCOMObject property and determines whether the Type is a COM object.
C# Syntax:
protected abstract bool IsCOMObjectImpl();
Return Value:
true if the Type is a COM object; otherwise, false.
Remarks

This method returns false for COM interfaces because they are not objects. COM interfaces can be implemented by Microsoft .NET Framework objects.

See also:
Type.IsCOMObject

Return to top


Method: IsContextfulImpl()
Summary
Implements the Type.IsContextful property and determines whether the Type can be hosted in a context.
C# Syntax:
protected virtual bool IsContextfulImpl();
Return Value:
true if the Type can be hosted in a context; otherwise, false.
Remarks
This method can be overridden by a derived class.

A context intercepts calls to the class members and enforce policies that are applied to the class, such as synchronization.

Example
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.";
}

    
See also:
Type.IsContextful

Return to top


Method: IsDefined(
   Type attributeType,
   bool inherit
)
Inherited
See base class member description: System.Reflection.MemberInfo.IsDefined

Summary
When overridden in a derived class, indicates whether one or more instance of attributeType is defined on this member.
C# Syntax:
public abstract bool IsDefined(
   Type attributeType,
   bool inherit
);
Parameters:

attributeType

The Type object to which the custom attributes are applied.

inherit

Specifies whether to search this member's inheritance chain to find the attributes.

Return Value:
true if one or more instance of attributeType is defined on this member; otherwise false.
Implements:
ICustomAttributeProvider.IsDefined
Example

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);
      }
   }
}

    

Return to top


Method: IsInstanceOfType(
   object o
)
Summary
Determines whether the specified object is an instance of the current Type.
C# Syntax:
public virtual bool IsInstanceOfType(
   object o
);
Parameters:

o

The object to compare with the current Type.

Return Value:
true if the current Type is in the inheritance hierarchy of the object represented by the o parameter, or if the current Type is an interface that o supports.false if neither of these conditions is the case, or if o is null.
Remarks
This method can be overridden by a derived class.
Example
The following example demonstrates the use of the IsInstanceOfType method.
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
              			
            

Return to top


Method: IsMarshalByRefImpl()
Summary
Implements the Type.IsMarshalByRef property and determines whether the Type is marshalled by reference.
C# Syntax:
protected virtual bool IsMarshalByRefImpl();
Return Value:
true if the Type is marshalled by reference; otherwise, false.
Remarks
This method can be overridden by a derived class.
Example
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.";
}

    
See also:
Type.IsMarshalByRef

Return to top


Method: IsPointerImpl()
Summary
When overridden in a derived class, implements the Type.IsPointer property and determines whether the Type is a pointer.
C# Syntax:
protected abstract bool IsPointerImpl();
Return Value:
true if the Type is a pointer; otherwise, false.
Remarks
See also:
Type.IsPointer

Return to top


Method: IsPrimitiveImpl()
Summary
When overridden in a derived class, implements the Type.IsPrimitive property and determines whether the Type is one of the primitive types.
C# Syntax:
protected abstract bool IsPrimitiveImpl();
Return Value:
true if the Type is one of the primitive types; otherwise, false.
Remarks
The primitive types are Boolean, Byte, SByte, Int16, UInt16, Int32, UInt32, Int64, UInt64, Char, Double, and Single.
Example
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);
      }
   }
}

    
See also:
Boolean | Byte | SByte | Int16 | UInt16 | Int32 | UInt32 | Int64 | UInt64 | Char | Double | Single | Type.IsPrimitive

Return to top


Method: IsSubclassOf(
   Type c
)
Summary
Determines whether the current Type derives from the specified Type.
C# Syntax:
public virtual bool IsSubclassOf(
   Type c
);
Parameters:

c

The Type to compare with the current Type.

Return Value:
true if the Type represented by the c parameter and the current Type represent classes, and the class represented by the current Type derives from the class represented by c; otherwise, false. This method also returns false if c and the current Type represent the same class.
Remarks
This method can be overridden by a derived class.
Example
The following example demonstrates the use of the IsSubclassOf method.
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
              			
            
See also:
Type.BaseType

Return to top


Method: IsValueTypeImpl()
Summary
Implements the Type.IsValueType property and determines whether the Type is a value type; that is, not a class or an interface.
C# Syntax:
protected virtual bool IsValueTypeImpl();
Return Value:
true if the Type is a value type; otherwise, false.
Remarks
Value types describe values that are represented as sequences of bits; value types are not classes or interfaces. These are referred to as "structs" in some programming languages. Enums are value types.
Example
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);
      }
   }
}

    
See also:
TypeAttributes | Type.IsClass | Type.IsInterface | ValueType | Type.IsValueType

Return to top


Method: MemberwiseClone()
Inherited
See base class member description: System.Object.MemberwiseClone
C# Syntax:
protected object MemberwiseClone();

For more information on members inherited from System.Object click on the link above.

Return to top


Overridden Method: ToString()
Summary
Returns a String representing the name of the current Type.
C# Syntax:
public override string ToString();
Return Value:
A String representing the name of the current Type.
Remarks
This method returns the fully qualified common language runtime namespace and name for all primitive types. For example, the C# instruction, (long)0.Type().ToString() returns "System.Int64" instead of merely "Int64".
Example

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 ); 
      }
   }
}

    
See also:
String

Return to top


Top of page

Copyright (c) 2002 Microsoft Corporation. All rights reserved.