System.Reflection.Emit.EnumBuilder Class

Assembly: Mscorlib.dll
Namespace: System.Reflection.Emit
Summary
Describes and represents an enumeration type.
C# Syntax:
public sealed class EnumBuilder : Type
Thread Safety
Reflection Emit is thread-safe when using assemblies that were created with the AppDomain.DefineDynamicAssembly method with the Boolean parameter isSynchronized set to true.
See also:
System.Reflection.Emit Namespace

System.Reflection.Emit.EnumBuilder Member List:

Public Properties
Assembly Read-only

Overridden:
Retrieves the dynamic assembly that contains this enum definition.
AssemblyQualifiedName Read-only

Overridden:
Returns the full path of this enum qualified by the display name of the parent assembly.
Attributes
(inherited from System.Type)
Read-only

See base class member description: System.Type.Attributes


Gets the attributes associated with the Type.
BaseType Read-only

Overridden:
Returns the parent Type of this type which is always Enum.
DeclaringType Read-only

Overridden:
Returns the type that declared this EnumBuilder.
FullName Read-only

Overridden:
Returns the full path of this enum.
GUID Read-only

Overridden:
Returns the GUID of this enum.
HasElementType
(inherited from System.Type)
Read-only

See base class member description: System.Type.HasElementType


Gets a value indicating whether the current Type encompasses or refers to another type; that is, whether the current Type is an array, a pointer, or is passed by reference.
IsAbstract
(inherited from System.Type)
Read-only

See base class member description: System.Type.IsAbstract


Gets a value indicating whether the Type is abstract and must be overridden.
IsAnsiClass
(inherited from System.Type)
Read-only

See base class member description: System.Type.IsAnsiClass


Gets a value indicating whether the string format attribute AnsiClass is selected for the Type.
IsArray
(inherited from System.Type)
Read-only

See base class member description: System.Type.IsArray


Gets a value indicating whether the Type is an array.
IsAutoClass
(inherited from System.Type)
Read-only

See base class member description: System.Type.IsAutoClass


Gets a value indicating whether the string format attribute AutoClass is selected for the Type.
IsAutoLayout
(inherited from System.Type)
Read-only

See base class member description: System.Type.IsAutoLayout


Gets a value indicating whether the class layout attribute AutoLayout is selected for the Type.
IsByRef
(inherited from System.Type)
Read-only

See base class member description: System.Type.IsByRef


Gets a value indicating whether the Type is passed by reference.
IsClass
(inherited from System.Type)
Read-only

See base class member description: System.Type.IsClass


Gets a value indicating whether the Type is a class; that is, not a value type or interface.
IsCOMObject
(inherited from System.Type)
Read-only

See base class member description: System.Type.IsCOMObject


Gets a value indicating whether the Type is a COM object.
IsContextful
(inherited from System.Type)
Read-only

See base class member description: System.Type.IsContextful


Gets a value indicating whether the Type can be hosted in a context.
IsEnum
(inherited from System.Type)
Read-only

See base class member description: System.Type.IsEnum


Gets a value indicating whether the current Type represents an enumeration.
IsExplicitLayout
(inherited from System.Type)
Read-only

See base class member description: System.Type.IsExplicitLayout


Gets a value indicating whether the class layout attribute ExplicitLayout is selected for the Type.
IsImport
(inherited from System.Type)
Read-only

See base class member description: System.Type.IsImport


Gets a value indicating whether the Type was imported from another class.
IsInterface
(inherited from System.Type)
Read-only

See base class member description: System.Type.IsInterface


Gets a value indicating whether the Type is an interface; that is, not a class or a value type.
IsLayoutSequential
(inherited from System.Type)
Read-only

See base class member description: System.Type.IsLayoutSequential


Gets a value indicating whether the class layout attribute SequentialLayout is selected for the Type.
IsMarshalByRef
(inherited from System.Type)
Read-only

See base class member description: System.Type.IsMarshalByRef


Gets a value indicating whether the Type is marshaled by reference.
IsNestedAssembly
(inherited from System.Type)
Read-only

See base class member description: System.Type.IsNestedAssembly


Gets a value indicating whether the Type is nested and visible only within its own assembly.
IsNestedFamANDAssem
(inherited from System.Type)
Read-only

See base class member description: System.Type.IsNestedFamANDAssem


Gets a value indicating whether the Type is nested and visible only to classes that belong to both its own family and its own assembly.
IsNestedFamily
(inherited from System.Type)
Read-only

See base class member description: System.Type.IsNestedFamily


Gets a value indicating whether the Type is nested and visible only within its own family.
IsNestedFamORAssem
(inherited from System.Type)
Read-only

See base class member description: System.Type.IsNestedFamORAssem


Gets a value indicating whether the Type is nested and visible only to classes that belong to either its own family or to its own assembly.
IsNestedPrivate
(inherited from System.Type)
Read-only

See base class member description: System.Type.IsNestedPrivate


Gets a value indicating whether the Type is nested and declared private.
IsNestedPublic
(inherited from System.Type)
Read-only

See base class member description: System.Type.IsNestedPublic


Gets a value indicating whether a class is nested and declared public.
IsNotPublic
(inherited from System.Type)
Read-only

See base class member description: System.Type.IsNotPublic


Gets a value indicating whether the top-level Type is not declared public.
IsPointer
(inherited from System.Type)
Read-only

See base class member description: System.Type.IsPointer


Gets a value indicating whether the Type is a pointer.
IsPrimitive
(inherited from System.Type)
Read-only

See base class member description: System.Type.IsPrimitive


Gets a value indicating whether the Type is one of the primitive types.
IsPublic
(inherited from System.Type)
Read-only

See base class member description: System.Type.IsPublic


Gets a value indicating whether the top-level Type is declared public.
IsSealed
(inherited from System.Type)
Read-only

See base class member description: System.Type.IsSealed


Gets a value indicating whether the Type is declared sealed.
IsSerializable
(inherited from System.Type)
Read-only

See base class member description: System.Type.IsSerializable


Gets a value indicating whether the Type is serializable.
IsSpecialName
(inherited from System.Type)
Read-only

See base class member description: System.Type.IsSpecialName


Gets a value indicating whether the Type has a name that requires special handling.
IsUnicodeClass
(inherited from System.Type)
Read-only

See base class member description: System.Type.IsUnicodeClass


Gets a value indicating whether the string format attribute UnicodeClass is selected for the Type.
IsValueType
(inherited from System.Type)
Read-only

See base class member description: System.Type.IsValueType


Gets a value indicating whether the Type is a value type.
MemberType
(inherited from System.Type)
Read-only

See base class member description: System.Type.MemberType


Gets a bitmask indicating the member type.
Module Read-only

Overridden:
Retrieves the dynamic module that contains this EnumBuilder definition.
Name Read-only

Overridden:
Returns the name of this enum.
Namespace Read-only

Overridden:
ReflectedType Read-only

Overridden:
Returns the type that was used to obtain this EnumBuilder.
TypeHandle Read-only

Overridden:
Retrieves the internal handle for this enum.
TypeInitializer
(inherited from System.Type)
Read-only

See base class member description: System.Type.TypeInitializer


Gets the initializer for the Type.
TypeToken Read-only

Returns the internal metadata type token of this enum.
UnderlyingField Read-only

Returns the underlying field for this enum.
UnderlyingSystemType Read-only

Overridden:
Returns the underlying system type for this enum.
Public Methods
CreateType Creates a Type object for this enum.
DefineLiteral Defines the named static field in an enumeration type with the specified constant value.
Equals
(inherited from System.Type)
Overloaded:
Equals(object o)

See base class member description: System.Type.Equals


Determines if the underlying system type of the current Type is the same as the underlying system type of the specified Object.
Equals
(inherited from System.Type)
Overloaded:
Equals(Type o)

See base class member description: System.Type.Equals


Determines if the underlying system type of the current Type is the same as the underlying system type of the specified Type.
FindInterfaces
(inherited from System.Type)
See base class member description: System.Type.FindInterfaces


Returns an array of Type objects representing a filtered list of interfaces implemented or inherited by the current Type.
FindMembers
(inherited from System.Type)
See base class member description: System.Type.FindMembers


Returns a filtered array of MemberInfo objects of the specified member type.
GetArrayRank
(inherited from System.Type)
See base class member description: System.Type.GetArrayRank


Gets the number of dimensions in an Array.
GetConstructor
(inherited from System.Type)
Overloaded:
GetConstructor(Type[] types)

See base class member description: System.Type.GetConstructor


Searches for a public instance constructor whose parameters match the types in the specified array.
GetConstructor
(inherited from System.Type)
Overloaded:
GetConstructor(BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers)

See base class member description: System.Type.GetConstructor


Searches for a constructor whose parameters match the specified argument types and modifiers, using the specified binding constraints.
GetConstructor
(inherited from System.Type)
Overloaded:
GetConstructor(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)

See base class member description: System.Type.GetConstructor


Searches for a constructor whose parameters match the specified argument types and modifiers, using the specified binding constraints and the specified calling convention.
GetConstructors
(inherited from System.Type)
Overloaded:
GetConstructors()

See base class member description: System.Type.GetConstructors


Returns all the public constructors defined for the current Type.
GetConstructors Overloaded:
GetConstructors(BindingFlags bindingAttr)

Overridden:
Returns an array of ConstructorInfo objects representing the public and non-public constructors defined for this class, as specified.
GetCustomAttributes Overloaded:
GetCustomAttributes(bool inherit)

Overridden:
Returns all the custom attributes defined for this constructor.
GetCustomAttributes Overloaded:
GetCustomAttributes(Type attributeType, bool inherit)

Overridden:
Returns the custom attributes identified by the given type.
GetDefaultMembers
(inherited from System.Type)
See base class member description: System.Type.GetDefaultMembers


Searches for the members defined for the current Type whose DefaultMemberAttribute is set.
GetElementType Overridden:
Calling this method always throws NotSupportedException.
GetEvent
(inherited from System.Type)
Overloaded:
GetEvent(string name)

See base class member description: System.Type.GetEvent


Returns the EventInfo object representing the specified event.
GetEvent Overloaded:
GetEvent(string name, BindingFlags bindingAttr)

Overridden:
Returns the event with the specified name.
GetEvents Overloaded:
GetEvents()

Overridden:
Returns the events for the public events declared or inherited by this type.
GetEvents Overloaded:
GetEvents(BindingFlags bindingAttr)

Overridden:
Returns the public and non-public events that are declared by this type.
GetField
(inherited from System.Type)
Overloaded:
GetField(string name)

See base class member description: System.Type.GetField


Searches for the field with the specified name.
GetField Overloaded:
GetField(string name, BindingFlags bindingAttr)

Overridden:
Returns the field specified by the given name.
GetFields
(inherited from System.Type)
Overloaded:
GetFields()

See base class member description: System.Type.GetFields


Returns all the public fields of the current Type.
GetFields Overloaded:
GetFields(BindingFlags bindingAttr)

Overridden:
Returns the public and non-public fields that are declared by this type.
GetHashCode
(inherited from System.Type)
See base class member description: System.Type.GetHashCode


Returns the hash code for this instance.
GetInterface
(inherited from System.Type)
Overloaded:
GetInterface(string name)

See base class member description: System.Type.GetInterface


Searches for the interface with the specified name.
GetInterface Overloaded:
GetInterface(string name, bool ignoreCase)

Overridden:
Returns the interface implemented (directly or indirectly) by this class with the fully-qualified name matching the given interface name.
GetInterfaceMap Overridden:
Returns an interface mapping for the interface requested.
GetInterfaces Overridden:
Returns an array of all the interfaces implemented on this a class and its base classes.
GetMember
(inherited from System.Type)
Overloaded:
GetMember(string name)

See base class member description: System.Type.GetMember


Searches for the members with the specified name.
GetMember
(inherited from System.Type)
Overloaded:
GetMember(string name, BindingFlags bindingAttr)

See base class member description: System.Type.GetMember


Searches for the specified members, using the specified binding constraints.
GetMember Overloaded:
GetMember(string name, MemberTypes type, BindingFlags bindingAttr)

Overridden:
Returns all the public and non-public members declared or inherited by this type, as specified.
GetMembers
(inherited from System.Type)
Overloaded:
GetMembers()

See base class member description: System.Type.GetMembers


Returns all the public members of the current Type.
GetMembers Overloaded:
GetMembers(BindingFlags bindingAttr)

Overridden:
Returns all the public and non-public members declared or inherited by this type, as specified.
GetMethod
(inherited from System.Type)
Overloaded:
GetMethod(string name)

See base class member description: System.Type.GetMethod


Searches for the public method with the specified name.
GetMethod
(inherited from System.Type)
Overloaded:
GetMethod(string name, BindingFlags bindingAttr)

See base class member description: System.Type.GetMethod


Searches for the specified method, using the specified binding constraints.
GetMethod
(inherited from System.Type)
Overloaded:
GetMethod(string name, Type[] types)

See base class member description: System.Type.GetMethod


Searches for the specified public method whose parameters match the specified argument types.
GetMethod
(inherited from System.Type)
Overloaded:
GetMethod(string name, Type[] types, ParameterModifier[] modifiers)

See base class member description: System.Type.GetMethod


Searches for the specified public method whose parameters match the specified argument types and modifiers.
GetMethod
(inherited from System.Type)
Overloaded:
GetMethod(string name, BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers)

See base class member description: System.Type.GetMethod


Searches for the specified method whose parameters match the specified argument types and modifiers, using the specified binding constraints.
GetMethod
(inherited from System.Type)
Overloaded:
GetMethod(string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)

See base class member description: System.Type.GetMethod


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
(inherited from System.Type)
Overloaded:
GetMethods()

See base class member description: System.Type.GetMethods


Returns all the public methods of the current Type.
GetMethods Overloaded:
GetMethods(BindingFlags bindingAttr)

Overridden:
Returns all the public and non-public methods declared or inherited by this type, as specified.
GetNestedType
(inherited from System.Type)
Overloaded:
GetNestedType(string name)

See base class member description: System.Type.GetNestedType


Searches for the nested type with the specified name.
GetNestedType Overloaded:
GetNestedType(string name, BindingFlags bindingAttr)

Overridden:
Returns the public and non-public nested types that are declared by this type.
GetNestedTypes
(inherited from System.Type)
Overloaded:
GetNestedTypes()

See base class member description: System.Type.GetNestedTypes


Returns all the types nested within the current Type.
GetNestedTypes Overloaded:
GetNestedTypes(BindingFlags bindingAttr)

Overridden:
Returns the public and non-public nested types that are declared or inherited by this type.
GetProperties
(inherited from System.Type)
Overloaded:
GetProperties()

See base class member description: System.Type.GetProperties


Returns all the public properties of the current Type.
GetProperties Overloaded:
GetProperties(BindingFlags bindingAttr)

Overridden:
Returns all the public and non-public properties declared or inherited by this type, as specified.
GetProperty
(inherited from System.Type)
Overloaded:
GetProperty(string name)

See base class member description: System.Type.GetProperty


Searches for the public property with the specified name.
GetProperty
(inherited from System.Type)
Overloaded:
GetProperty(string name, BindingFlags bindingAttr)

See base class member description: System.Type.GetProperty


Searches for the specified property, using the specified binding constraints.
GetProperty
(inherited from System.Type)
Overloaded:
GetProperty(string name, Type returnType)

See base class member description: System.Type.GetProperty


Searches for the public property with the specified name and return type.
GetProperty
(inherited from System.Type)
Overloaded:
GetProperty(string name, Type[] types)

See base class member description: System.Type.GetProperty


Searches for the specified public property whose parameters match the specified argument types.
GetProperty
(inherited from System.Type)
Overloaded:
GetProperty(string name, Type returnType, Type[] types)

See base class member description: System.Type.GetProperty


Searches for the specified public property whose parameters match the specified argument types.
GetProperty
(inherited from System.Type)
Overloaded:
GetProperty(string name, Type returnType, Type[] types, ParameterModifier[] modifiers)

See base class member description: System.Type.GetProperty


Searches for the specified public property whose parameters match the specified argument types and modifiers.
GetProperty
(inherited from System.Type)
Overloaded:
GetProperty(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers)

See base class member description: System.Type.GetProperty


Searches for the specified property whose parameters match the specified argument types and modifiers, using the specified binding constraints.
GetType
(inherited from System.Object)
See base class member description: System.Object.GetType

Derived from System.Object, the primary base class for all objects.
InvokeMember
(inherited from System.Type)
Overloaded:
InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args)

See base class member description: System.Type.InvokeMember


Invokes the specified member, using the specified binding constraints and matching the specified argument list.
InvokeMember
(inherited from System.Type)
Overloaded:
InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, CultureInfo culture)

See base class member description: System.Type.InvokeMember


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)

Overridden:
Invokes the specified member. The method that is to be invoked must be accessible and provide the most specific match with the specified argument list, under the contraints of the specified binder and invocation attributes.
IsAssignableFrom
(inherited from System.Type)
See base class member description: System.Type.IsAssignableFrom


Determines whether an instance of the current Type can be assigned from an instance of the specified Type.
IsDefined Overridden:
Checks if the specified custom attribute type is defined.
IsInstanceOfType
(inherited from System.Type)
See base class member description: System.Type.IsInstanceOfType


Determines whether the specified object is an instance of the current Type.
IsSubclassOf
(inherited from System.Type)
See base class member description: System.Type.IsSubclassOf


Determines whether the current Type derives from the specified Type.
SetCustomAttribute Overloaded:
SetCustomAttribute(CustomAttributeBuilder customBuilder)

Sets a custom attribute using a custom attribute builder.
SetCustomAttribute Overloaded:
SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)

Sets a custom attribute using a specified custom attribute blob.
ToString
(inherited from System.Type)
See base class member description: System.Type.ToString


Returns a String representing the name of the current Type.
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 Overridden:
Gets the implementation attribute flags.
GetConstructorImpl Overridden:
Searches for a constructor whose parameters match the specified argument types and modifiers, using the specified binding constraints and the specified calling convention.
GetMethodImpl Overridden:
Searches for the specified method whose parameters match the specified argument types and modifiers, using the specified binding constraints and the specified calling convention.
GetPropertyImpl Overridden:
Searches for the specified property whose parameters match the specified argument types and modifiers, using the specified binding constraints.
HasElementTypeImpl Overridden:
Calling this method always throws NotSupportedException.
IsArrayImpl Overridden:
IsByRefImpl Overridden:
Returns false.
IsCOMObjectImpl Overridden:
IsContextfulImpl
(inherited from System.Type)
See base class member description: System.Type.IsContextfulImpl


Implements the Type.IsContextful property and determines whether the Type can be hosted in a context.
IsMarshalByRefImpl
(inherited from System.Type)
See base class member description: System.Type.IsMarshalByRefImpl


Implements the Type.IsMarshalByRef property and determines whether the Type is marshalled by reference.
IsPointerImpl Overridden:
Returns false.
IsPrimitiveImpl Overridden:
IsValueTypeImpl Overridden:
MemberwiseClone
(inherited from System.Object)
See base class member description: System.Object.MemberwiseClone

Derived from System.Object, the primary base class for all objects.

Hierarchy:


System.Reflection.Emit.EnumBuilder Member Details

Overridden Property: Assembly (read-only)
Summary
Retrieves the dynamic assembly that contains this enum definition.
C# Syntax:
public override Assembly Assembly {get;}

Return to top


Overridden Property: AssemblyQualifiedName (read-only)
Summary
Returns the full path of this enum qualified by the display name of the parent assembly.
C# Syntax:
public override string AssemblyQualifiedName {get;}
Exceptions
Exception Type Condition
NotSupportedException If EnumBuilder.CreateType has not been called previously.
Remarks
The format of the returned string is:

<FullTypeName>, <AssemblyDisplayName>

See AssemblyName for a description of the format of the display name of an assembly.

Return to top


Property: Attributes (read-only)
Inherited
See base class member description: System.Type.Attributes

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

Return to top


Overridden Property: BaseType (read-only)
Summary
Returns the parent Type of this type which is always Enum.
C# Syntax:
public override Type BaseType {get;}

Return to top


Overridden Property: DeclaringType (read-only)
Summary
Returns the type that declared this EnumBuilder.
C# Syntax:
public override Type DeclaringType {get;}

Return to top


Overridden Property: FullName (read-only)
Summary
Returns the full path of this enum.
C# Syntax:
public override string FullName {get;}
Remarks
The returned format is "enclosingTypeFullName+nestedTypeName" for nested types and "typeName" for non-nested types.

Return to top


Overridden Property: GUID (read-only)
Summary
Returns the GUID of this enum.
C# Syntax:
public override Guid GUID {get;}
Exceptions
Exception Type Condition
NotSupportedException This method is not currently supported in types that are not complete.

Return to top


Property: HasElementType (read-only)
Inherited
See base class member description: System.Type.HasElementType

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)
Inherited
See base class member description: System.Type.IsAbstract

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)
Inherited
See base class member description: System.Type.IsAnsiClass

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)
Inherited
See base class member description: System.Type.IsArray

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)
Inherited
See base class member description: System.Type.IsAutoClass

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)
Inherited
See base class member description: System.Type.IsAutoLayout

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)
Inherited
See base class member description: System.Type.IsByRef

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)
Inherited
See base class member description: System.Type.IsClass

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)
Inherited
See base class member description: System.Type.IsCOMObject

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)
Inherited
See base class member description: System.Type.IsContextful

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)
Inherited
See base class member description: System.Type.IsEnum

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)
Inherited
See base class member description: System.Type.IsExplicitLayout

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)
Inherited
See base class member description: System.Type.IsImport

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)
Inherited
See base class member description: System.Type.IsInterface

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)
Inherited
See base class member description: System.Type.IsLayoutSequential

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)
Inherited
See base class member description: System.Type.IsMarshalByRef

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)
Inherited
See base class member description: System.Type.IsNestedAssembly

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)
Inherited
See base class member description: System.Type.IsNestedFamANDAssem

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)
Inherited
See base class member description: System.Type.IsNestedFamily

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)
Inherited
See base class member description: System.Type.IsNestedFamORAssem

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)
Inherited
See base class member description: System.Type.IsNestedPrivate

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)
Inherited
See base class member description: System.Type.IsNestedPublic

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)
Inherited
See base class member description: System.Type.IsNotPublic

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)
Inherited
See base class member description: System.Type.IsPointer

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)
Inherited
See base class member description: System.Type.IsPrimitive

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)
Inherited
See base class member description: System.Type.IsPublic

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)
Inherited
See base class member description: System.Type.IsSealed

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)
Inherited
See base class member description: System.Type.IsSerializable

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)
Inherited
See base class member description: System.Type.IsSpecialName

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)
Inherited
See base class member description: System.Type.IsUnicodeClass

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)
Inherited
See base class member description: System.Type.IsValueType

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


Property: MemberType (read-only)
Inherited
See base class member description: System.Type.MemberType

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


Overridden Property: Module (read-only)
Summary
Retrieves the dynamic module that contains this EnumBuilder definition.
C# Syntax:
public override Module Module {get;}

Return to top


Overridden Property: Name (read-only)
Summary
Returns the name of this enum.
C# Syntax:
public override string Name {get;}

Return to top


Overridden Property: Namespace (read-only)
Summary
Returns the namespace of this enum.
C# Syntax:
public override string Namespace {get;}

Return to top


Overridden Property: ReflectedType (read-only)
Summary
Returns the type that was used to obtain this EnumBuilder.
C# Syntax:
public override Type ReflectedType {get;}

Return to top


Overridden Property: TypeHandle (read-only)
Summary
Retrieves the internal handle for this enum.
C# Syntax:
public override RuntimeTypeHandle TypeHandle {get;}
Exceptions
Exception Type Condition
NotSupportedException This property is not currently supported.
Remarks
You can retrieve the type using Type.GetType or Assembly.GetType and use reflection on the retrieved type.

Use this handle to access the underlying metadata handle.

Return to top


Property: TypeInitializer (read-only)
Inherited
See base class member description: System.Type.TypeInitializer

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: TypeToken (read-only)
Summary
Returns the internal metadata type token of this enum.
C# Syntax:
public TypeToken TypeToken {get;}

Return to top


Property: UnderlyingField (read-only)
Summary
Returns the underlying field for this enum.
C# Syntax:
public FieldBuilder UnderlyingField {get;}

Return to top


Overridden Property: UnderlyingSystemType (read-only)
Summary
Returns the underlying system type for this enum.
C# Syntax:
public override Type UnderlyingSystemType {get;}
Implements:
IReflect.UnderlyingSystemType

Return to top


Method: CreateType()
Summary
Creates a Type object for this enum.
C# Syntax:
public Type CreateType();
Return Value:
A Type object for this enum.
Exceptions
Exception Type Condition
InvalidOperationException This type has been previously created.

-or-

The enclosing type has not been created.

Return to top


Method: DefineLiteral(
   string literalName,
   object literalValue
)
Summary
Defines the named static field in an enumeration type with the specified constant value.
C# Syntax:
public FieldBuilder DefineLiteral(
   string literalName,
   object literalValue
);
Parameters:

literalName

The name of the static field.

literalValue

The constant value of the literal.

Return Value:
The defined field.
Remarks
The defined field will have the field attributes FieldAttributes.Public, FieldAttributes.Static, and FieldAttributes.Literal set.

Return to top


Overloaded Method: Equals(
   object o
)
Inherited
See base class member description: System.Type.Equals

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
)
Inherited
See base class member description: System.Type.Equals

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:
~EnumBuilder();

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

Return to top


Method: FindInterfaces(
   TypeFilter filter,
   object filterCriteria
)
Inherited
See base class member description: System.Type.FindInterfaces

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
)
Inherited
See base class member description: System.Type.FindMembers

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()
Inherited
See base class member description: System.Type.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


Overridden Method: GetAttributeFlagsImpl()
Summary
Gets the implementation attribute flags.
C# Syntax:
protected override TypeAttributes GetAttributeFlagsImpl();
Return Value:
The implementation attribute flags.

Return to top


Overloaded Method: GetConstructor(
   Type[] types
)
Inherited
See base class member description: System.Type.GetConstructor

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
)
Inherited
See base class member description: System.Type.GetConstructor

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
)
Inherited
See base class member description: System.Type.GetConstructor

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


Overridden Method: GetConstructorImpl(
   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:
protected override 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 conduct a case-sensitive search for public methods.

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

-or-

Zero, to conduct a case-sensitive search for public methods.

binder

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

Return Value:
A ConstructorInfo object representing the constructor that matches the specified requirements, if found; otherwise, null.
Exceptions
Exception Type Condition
NotSupportedException This method is not currently supported in types that are not complete.
Remarks
As a workaround to retrieve the constructor of a finished type, you can retrieve the type using Type.GetType or Assembly.GetType and use reflection on the retrieved type.

Return to top


Overloaded Method: GetConstructors()
Inherited
See base class member description: System.Type.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
Returns an array of ConstructorInfo objects representing the public and non-public constructors defined for this class, as specified.
C# Syntax:
public override ConstructorInfo[] GetConstructors(
   BindingFlags bindingAttr
);
Parameters:

bindingAttr

This must be a bit flag from BindingFlags: InvokeMethod, NonPublic, and so on.

Return Value:
Returns an array of ConstructorInfo objects representing the specified constructors defined for this class. If no constructors are defined, an empty array is returned.
Exceptions
Exception Type Condition
NotSupportedException This method is not currently supported in types that are not complete.
Remarks
As a workaround, to retrieve the constructor of a finished type, you can retrieve the type using Type.GetType or Assembly.GetType and use reflection on the retrieved type.

Return to top


Overloaded Method: GetCustomAttributes(
   bool inherit
)
Summary
Returns all the custom attributes defined for this constructor.
C# Syntax:
public override object[] GetCustomAttributes(
   bool inherit
);
Parameters:

inherit

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

Return Value:
Returns an array of objects representing all the custom attributes of the constructor represented by this ConstructorBuilder instance.
Exceptions
Exception Type Condition
NotSupportedException This method is not currently supported in types that are not complete.
Implements:
ICustomAttributeProvider.GetCustomAttributes
Remarks
As a workaround, to retrieve the custom attributes of a finished type, retrieve the type using Type.GetType and call MemberInfo.GetCustomAttributes on the returned Type.

Return to top


Overloaded Method: GetCustomAttributes(
   Type attributeType,
   bool inherit
)
Summary
Returns the custom attributes identified by the given type.
C# Syntax:
public override object[] GetCustomAttributes(
   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:
Returns an array of objects representing the attributes of this constructor that are of TypeattributeType.
Exceptions
Exception Type Condition
NotSupportedException This method is not currently supported in types that are not complete.
Implements:
ICustomAttributeProvider.GetCustomAttributes
Remarks
As a workaround, to retrieve the custom attributes of a finished type, retrieve the type using Type.GetType and call MemberInfo.GetCustomAttributes on the returned Type.

Return to top


Method: GetDefaultMembers()
Inherited
See base class member description: System.Type.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


Overridden Method: GetElementType()
Summary
Calling this method always throws NotSupportedException.
C# Syntax:
public override Type GetElementType();
Return Value:
This method is not supported. No value is returned.
Exceptions
Exception Type Condition
NotSupportedException This method is not currently supported.

Return to top


Overloaded Method: GetEvent(
   string name
)
Inherited
See base class member description: System.Type.GetEvent

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
Returns the event with the specified name.
C# Syntax:
public override EventInfo GetEvent(
   string name,
   BindingFlags bindingAttr
);
Parameters:

name

The name of the event to get.

bindingAttr

This invocation attribute. This must be a bit flag from BindingFlags: InvokeMethod, NonPublic, and so on.

Return Value:
Returns an EventInfo object representing the event declared or inherited by this type with the specified name. If there are no matches, then an empty array is returned.
Exceptions
Exception Type Condition
NotSupportedException This method is not currently supported in types that are not complete.
Remarks
As a workaround, to retrieve the event of a finished type, retrieve the type using Type.GetType or Assembly.GetType and use reflection on the retrieved type.

Return to top


Overloaded Method: GetEvents()
Summary
Returns the events for the public events declared or inherited by this type.
C# Syntax:
public override EventInfo[] GetEvents();
Return Value:
Returns an array of EventInfo objects representing the public events declared or inherited by this type. An empty array is returned if there are no public events.
Exceptions
Exception Type Condition
NotSupportedException This method is not currently supported in types that are not complete.
Remarks
As a workaround, to retrieve the events of a finished type, retrieve the type using Type.GetType or Assembly.GetType and use reflection on the retrieved type.

Return to top


Overloaded Method: GetEvents(
   BindingFlags bindingAttr
)
Summary
Returns the public and non-public events that are declared by this type.
C# Syntax:
public override EventInfo[] GetEvents(
   BindingFlags bindingAttr
);
Parameters:

bindingAttr

This must be a bit flag from BindingFlags, such as InvokeMethod, NonPublic, and so on.

Return Value:
Returns an array of EventInfo objects representing the public and non-public events declared or inherited by this type. An empty array is returned if there are no events, as specified.
Exceptions
Exception Type Condition
NotSupportedException This method is not currently supported in types that are not complete.
Remarks
As a workaround, to retrieve the events of a finished type, retrieve Retrieve the type using Type.GetType or Assembly.GetType and use reflection on the retrieved type to retrieve the events.

Return to top


Overloaded Method: GetField(
   string name
)
Inherited
See base class member description: System.Type.GetField

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
Returns the field specified by the given name.
C# Syntax:
public override FieldInfo GetField(
   string name,
   BindingFlags bindingAttr
);
Parameters:

name

The name of the field to get.

bindingAttr

This must be a bit flag from BindingFlags: InvokeMethod, NonPublic, and so on.

Return Value:
Returns the FieldInfo object representing the field declared or inherited by this type with the specified name and public or non-public modifier. If there are no matches, then null is returned.
Exceptions
Exception Type Condition
NotSupportedException This method is not currently supported in types that are not complete.
Implements:
IReflect.GetField
Remarks
As a workaround, to retrieve the field of a finished type, retrieve the type using Type.GetType or Assembly.GetType and use reflection on the retrieved type.

Return to top


Overloaded Method: GetFields()
Inherited
See base class member description: System.Type.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
Returns the public and non-public fields that are declared by this type.
C# Syntax:
public override FieldInfo[] GetFields(
   BindingFlags bindingAttr
);
Parameters:

bindingAttr

This must be a bit flag from BindingFlags, such as InvokeMethod, NonPublic, and so on.

Return Value:
Returns an array of FieldInfo objects representing the public and non-public fields declared or inherited by this type. An empty array is returned if there are no fields, as specified.
Exceptions
Exception Type Condition
NotSupportedException This method is not currently supported in types that are not complete.
Implements:
IReflect.GetFields
Remarks
As a workaround, to retrieve the field of a finished type, retrieve the type using Type.GetType or Assembly.GetType and use reflection on the retrieved type.

Return to top


Method: GetHashCode()
Inherited
See base class member description: System.Type.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
)
Inherited
See base class member description: System.Type.GetInterface

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
Returns the interface implemented (directly or indirectly) by this class with the fully-qualified name matching the given interface name.
C# Syntax:
public override Type GetInterface(
   string name,
   bool ignoreCase
);
Parameters:

name

The name of the interface.

ignoreCase

If true, the search is case-insensitive. If false, the search is case-sensitive.

Return Value:
Returns a Type object representing the implemented interface. Returns null if no interface matching name is found.
Exceptions
Exception Type Condition
NotSupportedException This method is not currently supported in types that are not complete.
Remarks
As a workaround, to retrieve the interface of a finished type, retrieve the type using Type.GetType or Assembly.GetType and use reflection on the retrieved type.

Return to top


Overridden Method: GetInterfaceMap(
   Type interfaceType
)
Summary
Returns an interface mapping for the interface requested.
C# Syntax:
public override InterfaceMapping GetInterfaceMap(
   Type interfaceType
);
Parameters:

interfaceType

The type of the interface for which the interface mapping is to be retrieved.

Return Value:
The requested interface mapping.
Exceptions
Exception Type Condition
ArgumentException The type does not implement the interface.
Remarks
As a workaround, to retrieve the interface mapping types of a finished type, retrieve the type using Type.GetType or Assembly.GetType and use reflection on the retrieved type.

Return to top


Overridden Method: GetInterfaces()
Summary
Returns an array of all the interfaces implemented on this a class and its base classes.
C# Syntax:
public override Type[] GetInterfaces();
Return Value:
Returns an array of Type objects representing the implemented interfaces. If none are defined, an empty array is returned.

Return to top


Overloaded Method: GetMember(
   string name
)
Inherited
See base class member description: System.Type.GetMember

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
)
Inherited
See base class member description: System.Type.GetMember

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
Returns all the public and non-public members declared or inherited by this type, as specified.
C# Syntax:
public override MemberInfo[] GetMember(
   string name,
   MemberTypes type,
   BindingFlags bindingAttr
);
Parameters:

name

The name of the member.

type

The type of member that is to be returned.

bindingAttr

This must be a bit flag from BindingFlags: InvokeMethod, NonPublic, and so on.

Return Value:
Returns an array of MemberInfo objects representing the public and non-public members defined on this type if nonPublic is used; otherwise, only the public members are returned.
Exceptions
Exception Type Condition
NotSupportedException This method is not currently supported in types that are not complete.
Remarks
As a workaround, to retrieve the member of a finished type, retrieve the type using Type.GetType or Assembly.GetType and use reflection on the retrieved type.

Return to top


Overloaded Method: GetMembers()
Inherited
See base class member description: System.Type.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
Returns all the public and non-public members declared or inherited by this type, as specified.
C# Syntax:
public override MemberInfo[] GetMembers(
   BindingFlags bindingAttr
);
Parameters:

bindingAttr

This must be a bit flag from BindingFlags: InvokeMethod, NonPublic, and so on.

Return Value:
Returns an array of MemberInfo objects representing the public and non-public members declared or inherited by this type. An empty array is returned if there are no matching members.
Exceptions
Exception Type Condition
NotSupportedException This method is not currently supported in types that are not complete.
Implements:
IReflect.GetMembers
Remarks
As a workaround, to retrieve the members of a finished type, retrieve the type using Type.GetType or Assembly.GetType and use reflection on the retrieved type.

Return to top


Overloaded Method: GetMethod(
   string name
)
Inherited
See base class member description: System.Type.GetMethod

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
)
Inherited
See base class member description: System.Type.GetMethod

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
)
Inherited
See base class member description: System.Type.GetMethod

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
)
Inherited
See base class member description: System.Type.GetMethod

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
)
Inherited
See base class member description: System.Type.GetMethod

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
)
Inherited
See base class member description: System.Type.GetMethod

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


Overridden Method: GetMethodImpl(
   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:
protected override 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 conduct a case-sensitive search for public methods.

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

-or-

Zero, to conduct a case-sensitive search for public methods.

binder

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.

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.

Return Value:
A MethodInfo object representing the method that matches the specified requirements, if found; otherwise, null.
Exceptions
Exception Type Condition
NotSupportedException This method is not currently supported in types that are not complete.
Remarks
As a workaround, to retrieve the method, retrieve the type using Type.GetType or Assembly.GetType and use reflection on the retrieved type.

Return to top


Overloaded Method: GetMethods()
Inherited
See base class member description: System.Type.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
Returns all the public and non-public methods declared or inherited by this type, as specified.
C# Syntax:
public override MethodInfo[] GetMethods(
   BindingFlags bindingAttr
);
Parameters:

bindingAttr

This must be a bit flag from BindingFlags, such as InvokeMethod, NonPublic, and so on.

Return Value:
Returns an array of MethodInfo objects representing the public and non-public methods defined on this type if nonPublic is used; otherwise, only the public methods are returned.
Exceptions
Exception Type Condition
NotSupportedException This method is not currently supported in types that are not complete.
Implements:
IReflect.GetMethods
Remarks
As a workaround, to retrieve the methods of a finished type, retrieve the type using Type.GetType or Assembly.GetType and use reflection on the retrieved type.

Return to top


Overloaded Method: GetNestedType(
   string name
)
Inherited
See base class member description: System.Type.GetNestedType

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
Returns the public and non-public nested types that are declared by this type.
C# Syntax:
public override 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 conduct a case-sensitive search for public methods.

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

-or-

Zero, to conduct a case-sensitive search for public methods.

Return Value:
A Type object representing the nested type that matches the specified requirements, if found; otherwise, null.
Exceptions
Exception Type Condition
NotSupportedException This method is not currently supported in types that are not complete.
Remarks
As a workaround, to retrieve the nested type of a finished type, retrieve the type using Type.GetType or Assembly.GetType and use reflection on the retrieved type.

Return to top


Overloaded Method: GetNestedTypes()
Inherited
See base class member description: System.Type.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
Returns the public and non-public nested types that are declared or inherited by this type.
C# Syntax:
public override Type[] GetNestedTypes(
   BindingFlags bindingAttr
);
Parameters:

bindingAttr

This must be a bit flag from BindingFlags, such as InvokeMethod, NonPublic, and so on.

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

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.

Exceptions
Exception Type Condition
NotSupportedException This method is not currently supported in types that are not complete.
Remarks
As a workaround, to retrieve the nested types of a finished type, retrieve the type using Type.GetType or Assembly.GetType and use reflection on the retrieved type.

Return to top


Overloaded Method: GetProperties()
Inherited
See base class member description: System.Type.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
Returns all the public and non-public properties declared or inherited by this type, as specified.
C# Syntax:
public override PropertyInfo[] GetProperties(
   BindingFlags bindingAttr
);
Parameters:

bindingAttr

This invocation attribute. This must be a bit flag from BindingFlags: InvokeMethod, NonPublic, and so on.

Return Value:
Returns an array of PropertyInfo objects representing the public and non-public properties defined on this type if nonPublic is used; otherwise, only the public properties are returned.
Exceptions
Exception Type Condition
NotSupportedException This method is not currently supported in types that are not complete.
Implements:
IReflect.GetProperties
Remarks
As a workaround, to retrieve the properties of a finished type, retrieve the type using Type.GetType or Assembly.GetType and use reflection on the retrieved type.

Return to top


Overloaded Method: GetProperty(
   string name
)
Inherited
See base class member description: System.Type.GetProperty

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
)
Inherited
See base class member description: System.Type.GetProperty

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
)
Inherited
See base class member description: System.Type.GetProperty

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
)
Inherited
See base class member description: System.Type.GetProperty

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
)
Inherited
See base class member description: System.Type.GetProperty

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
)
Inherited
See base class member description: System.Type.GetProperty

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
)
Inherited
See base class member description: System.Type.GetProperty

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


Overridden Method: GetPropertyImpl(
   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:
protected override 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 conduct a case-sensitive search for public properties.

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

-or-

Zero, to conduct a case-sensitive search for public properties.

binder

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.

Return Value:
A PropertyInfo object representing the property that matches the specified requirements, if found; otherwise, null.
Exceptions
Exception Type Condition
NotSupportedException This method is not currently supported in types that are not complete.
Remarks
As a workaround, to retrieve the property of a finished type, retrieve the type using Type.GetType or Assembly.GetType and use reflection on the retrieved type.

Return to top


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


Overridden Method: HasElementTypeImpl()
Summary
Calling this method always throws NotSupportedException.
C# Syntax:
protected override bool HasElementTypeImpl();
Return Value:
This method is not supported. No value is returned.
Exceptions
Exception Type Condition
NotSupportedException This method is not supported.
Remarks
Retrieve the type using Type.GetType or Assembly.GetType and use reflection on the retrieved type.

Return to top


Overloaded Method: InvokeMember(
   string name,
   BindingFlags invokeAttr,
   Binder binder,
   object target,
   object[] args
)
Inherited
See base class member description: System.Type.InvokeMember

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
)
Inherited
See base class member description: System.Type.InvokeMember

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
Invokes the specified member. The method that is to be invoked must be accessible and provide the most specific match with the specified argument list, under the contraints of the specified binder and invocation attributes.
C# Syntax:
public override object InvokeMember(
   string name,
   BindingFlags invokeAttr,
   Binder binder,
   object target,
   object[] args,
   ParameterModifier[] modifiers,
   CultureInfo culture,
   string[] namedParameters
);
Parameters:

name

The name of the member to invoke. This can be a constructor, method, property, or field. A suitable invocation attribute must be specified. Note that it is possible to invoke the default member of a class by passing an empty string as the name of the member.

invokeAttr

The invocation attribute. This must be a bit flag from BindingFlags.

binder

An object that enables the binding, coercion of argument types, invocation of members, and retrieval of MemberInfo objects using reflection. If binder is null, the default binder is used. See Binder.

target

The object on which to invoke the specified member. If the member is static, this parameter is ignored.

args

An argument list. This is an array of objects that contains the number, order, and type of the parameters of the member to be invoked. If there are no parameters this should be null.

modifiers

An array of the same length as args with elements that represent the attributes associated with the arguments of the member to be invoked. A parameter has attributes associated with it in the metadata. They are used by various interoperability services. See the metadata specs for details such as this.

culture

An instance of CultureInfo used to govern the coercion of types. If this is null, the CultureInfo for the current thread is used. (Note that this is necessary to, for example, convert a string that represents 1000 to a double value, since 1000 is represented differently by different cultures.)

namedParameters

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.

Return Value:
Returns the return value of the invoked member.
Exceptions
Exception Type Condition
NotSupportedException This method is not currently supported in types that are not complete.
Implements:
IReflect.InvokeMember
Remarks
You can retrieve the type using Type.GetType or Assembly.GetType and use reflection on the retrieved type.

Return to top


Overridden Method: IsArrayImpl()
Summary
Returns false.
C# Syntax:
protected override bool IsArrayImpl();
Return Value:
false

Return to top


Method: IsAssignableFrom(
   Type c
)
Inherited
See base class member description: System.Type.IsAssignableFrom

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


Overridden Method: IsByRefImpl()
Summary
Returns false.
C# Syntax:
protected override bool IsByRefImpl();
Return Value:
true

Return to top


Overridden Method: IsCOMObjectImpl()
Summary
Returns false.
C# Syntax:
protected override bool IsCOMObjectImpl();
Return Value:
false

Return to top


Method: IsContextfulImpl()
Inherited
See base class member description: System.Type.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


Overridden Method: IsDefined(
   Type attributeType,
   bool inherit
)
Summary
Checks if the specified custom attribute type is defined.
C# Syntax:
public override 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.
Exceptions
Exception Type Condition
NotSupportedException This method is not currently supported in types that are not complete.
Implements:
ICustomAttributeProvider.IsDefined
Remarks
As a workaround, to check if a custom attribute is defined for a finished type, retrieve the type using Type.GetType and call MemberInfo.GetCustomAttributes on the returned Type.

Return to top


Method: IsInstanceOfType(
   object o
)
Inherited
See base class member description: System.Type.IsInstanceOfType

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()
Inherited
See base class member description: System.Type.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


Overridden Method: IsPointerImpl()
Summary
Returns false.
C# Syntax:
protected override bool IsPointerImpl();
Return Value:
true

Return to top


Overridden Method: IsPrimitiveImpl()
Summary
Returns false.
C# Syntax:
protected override bool IsPrimitiveImpl();
Return Value:
false

Return to top


Method: IsSubclassOf(
   Type c
)
Inherited
See base class member description: System.Type.IsSubclassOf

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


Overridden Method: IsValueTypeImpl()
Summary
Returns true.
C# Syntax:
protected override bool IsValueTypeImpl();
Return Value:
true

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


Overloaded Method: SetCustomAttribute(
   CustomAttributeBuilder customBuilder
)
Summary
Sets a custom attribute using a custom attribute builder.
C# Syntax:
public void SetCustomAttribute(
   CustomAttributeBuilder customBuilder
);
Parameters:

customBuilder

An instance of a helper class to define the custom attribute.

Exceptions
Exception Type Condition
ArgumentNullException con is null.

Return to top


Overloaded Method: SetCustomAttribute(
   ConstructorInfo con,
   byte[] binaryAttribute
)
Summary
Sets a custom attribute using a specified custom attribute blob.
C# Syntax:
public void SetCustomAttribute(
   ConstructorInfo con,
   byte[] binaryAttribute
);
Parameters:

con

The constructor for the custom attribute.

binaryAttribute

A byte blob representing the attributes.

Exceptions
Exception Type Condition
ArgumentNullException con or binaryAttribute is null.
Remarks
See the metadata specification for details on how to format binaryAttribute.

Return to top


Method: ToString()
Inherited
See base class member description: System.Type.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.