[Serializable] |
This class is the primary way to access metadata, and it acts as a gateway to the Reflection API. Use the members of Type to get information about a type declaration, such as the constructors, methods, fields, properties, and events of a class, as well as the module and the assembly in which the class is deployed.
A Type object that represents a type is unique; that is, two Type object references refer to the same object if and only if they represent the same type. This allows for the synchronization of multiple static method invocations and for comparison of Type objects using reference equality.
This class is thread safe; multiple threads can concurrently read from or write to an instance of this type. An instance of Type can represent any of the following types:
A reference to the Type object associated with a type can be obtained in the following ways.
| Delimiter | Separates names in the namespace of the Type. This field is read-only. |
| EmptyTypes | Represents an empty array of type Type. This field is read-only. |
| FilterAttribute | Represents the member filter used on attributes. This field is read-only. |
| FilterName | Represents the case-sensitive member filter used on names. This field is read-only. |
| FilterNameIgnoreCase | Represents the case-insensitive member filter used on names. This field is read-only. |
| Missing | Represents a missing value in the Type information. This field is read-only. |
| Assembly | Read-only Gets the Assembly that the type is declared in. |
| AssemblyQualifiedName | Read-only Gets the fully qualified name of the Type, including the name of the assembly from which the Type was loaded. |
| Attributes | Read-only Gets the attributes associated with the Type. |
| BaseType | Read-only Gets the type from which the current Type directly inherits. |
| DeclaringType | Read-only Overridden: Gets the class that declares this member. |
| DefaultBinder | Read-only Gets the default binder used by the system. |
| FullName | Read-only Gets the fully qualified name of the Type, including the namespace of the Type. |
| GUID | Read-only Gets the GUID associated with the Type. |
| HasElementType | Read-only Gets a value indicating whether the current Type encompasses or refers to another type; that is, whether the current Type is an array, a pointer, or is passed by reference. |
| IsAbstract | Read-only Gets a value indicating whether the Type is abstract and must be overridden. |
| IsAnsiClass | Read-only Gets a value indicating whether the string format attribute AnsiClass is selected for the Type. |
| IsArray | Read-only Gets a value indicating whether the Type is an array. |
| IsAutoClass | Read-only Gets a value indicating whether the string format attribute AutoClass is selected for the Type. |
| IsAutoLayout | Read-only Gets a value indicating whether the class layout attribute AutoLayout is selected for the Type. |
| IsByRef | Read-only Gets a value indicating whether the Type is passed by reference. |
| IsClass | Read-only Gets a value indicating whether the Type is a class; that is, not a value type or interface. |
| IsCOMObject | Read-only Gets a value indicating whether the Type is a COM object. |
| IsContextful | Read-only Gets a value indicating whether the Type can be hosted in a context. |
| IsEnum | Read-only Gets a value indicating whether the current Type represents an enumeration. |
| IsExplicitLayout | Read-only Gets a value indicating whether the class layout attribute ExplicitLayout is selected for the Type. |
| IsImport | Read-only Gets a value indicating whether the Type was imported from another class. |
| IsInterface | Read-only Gets a value indicating whether the Type is an interface; that is, not a class or a value type. |
| IsLayoutSequential | Read-only Gets a value indicating whether the class layout attribute SequentialLayout is selected for the Type. |
| IsMarshalByRef | Read-only Gets a value indicating whether the Type is marshaled by reference. |
| IsNestedAssembly | Read-only Gets a value indicating whether the Type is nested and visible only within its own assembly. |
| IsNestedFamANDAssem | Read-only Gets a value indicating whether the Type is nested and visible only to classes that belong to both its own family and its own assembly. |
| IsNestedFamily | Read-only Gets a value indicating whether the Type is nested and visible only within its own family. |
| IsNestedFamORAssem | Read-only Gets a value indicating whether the Type is nested and visible only to classes that belong to either its own family or to its own assembly. |
| IsNestedPrivate | Read-only Gets a value indicating whether the Type is nested and declared private. |
| IsNestedPublic | Read-only Gets a value indicating whether a class is nested and declared public. |
| IsNotPublic | Read-only Gets a value indicating whether the top-level Type is not declared public. |
| IsPointer | Read-only Gets a value indicating whether the Type is a pointer. |
| IsPrimitive | Read-only Gets a value indicating whether the Type is one of the primitive types. |
| IsPublic | Read-only Gets a value indicating whether the top-level Type is declared public. |
| IsSealed | Read-only Gets a value indicating whether the Type is declared sealed. |
| IsSerializable | Read-only Gets a value indicating whether the Type is serializable. |
| IsSpecialName | Read-only Gets a value indicating whether the Type has a name that requires special handling. |
| IsUnicodeClass | Read-only Gets a value indicating whether the string format attribute UnicodeClass is selected for the Type. |
| IsValueType | Read-only Gets a value indicating whether the Type is a value type. |
| MemberType | Read-only Overridden: Gets a bitmask indicating the member type. |
| Module | Read-only Gets the module (the DLL) in which the current Type is defined. |
| Name (inherited from System.Reflection.MemberInfo) |
Read-only See base class member description: System.Reflection.MemberInfo.Name Gets the name of this member. |
| Namespace | Read-only Gets the namespace of the Type. |
| ReflectedType | Read-only Overridden: Gets the class object that was used to obtain this member. |
| TypeHandle | Read-only Gets the handle for the current Type. |
| TypeInitializer | Read-only Gets the initializer for the Type. |
| UnderlyingSystemType | Read-only Indicates the type provided by the common language runtime that represents this type. |
| Equals | Overloaded:Equals(object o)Overridden: Determines if the underlying system type of the current Type is the same as the underlying system type of the specified Object. |
| Equals | Overloaded:Equals(Type o) Determines if the underlying system type of the current Type is the same as the underlying system type of the specified Type. |
| FindInterfaces | Returns an array of Type objects representing a filtered list of interfaces implemented or inherited by the current Type. |
| FindMembers | Returns a filtered array of MemberInfo objects of the specified member type. |
| GetArrayRank | Gets the number of dimensions in an Array. |
| GetConstructor | Overloaded:GetConstructor(Type[] types) Searches for a public instance constructor whose parameters match the types in the specified array. |
| GetConstructor | Overloaded:GetConstructor(BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers) Searches for a constructor whose parameters match the specified argument types and modifiers, using the specified binding constraints. |
| GetConstructor | Overloaded:GetConstructor(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) Searches for a constructor whose parameters match the specified argument types and modifiers, using the specified binding constraints and the specified calling convention. |
| GetConstructors | Overloaded:GetConstructors() Returns all the public constructors defined for the current Type. |
| GetConstructors | Overloaded:GetConstructors(BindingFlags bindingAttr) When overridden in a derived class, searches for the constructors defined for the current Type, using the specified BindingFlags. |
| GetCustomAttributes (inherited from System.Reflection.MemberInfo) |
Overloaded:GetCustomAttributes(bool inherit)See base class member description: System.Reflection.MemberInfo.GetCustomAttributesWhen overridden in a derived class, returns an array of all of the custom attributes. |
| GetCustomAttributes (inherited from System.Reflection.MemberInfo) |
Overloaded:GetCustomAttributes(Type attributeType, bool inherit)See base class member description: System.Reflection.MemberInfo.GetCustomAttributesWhen overridden in a derived class, returns an array of custom attributes identified by Type. |
| GetDefaultMembers | Searches for the members defined for the current Type whose DefaultMemberAttribute is set. |
| GetElementType | When overridden in a derived class, returns the Type of the object encompassed or referred to by the current array, pointer or reference type. |
| GetEvent | Overloaded:GetEvent(string name) Returns the EventInfo object representing the specified event. |
| GetEvent | Overloaded:GetEvent(string name, BindingFlags bindingAttr) When overridden in a derived class, returns the EventInfo object representing the specified event, using the specified binding constraints. |
| GetEvents | Overloaded:GetEvents() Returns all the public events that are declared or inherited by the current Type. |
| GetEvents | Overloaded:GetEvents(BindingFlags bindingAttr) When overridden in a derived class, searches for events that are declared or inherited by the current Type, using the specified binding constraints. |
| GetField | Overloaded:GetField(string name) Searches for the field with the specified name. |
| GetField | Overloaded:GetField(string name, BindingFlags bindingAttr) Searches for the specified field, using the specified binding constraints. |
| GetFields | Overloaded:GetFields() Returns all the public fields of the current Type. |
| GetFields | Overloaded:GetFields(BindingFlags bindingAttr) When overridden in a derived class, searches for the fields defined for the current Type, using the specified binding constraints. |
| GetHashCode | Overridden: Returns the hash code for this instance. |
| GetInterface | Overloaded:GetInterface(string name) Searches for the interface with the specified name. |
| GetInterface | Overloaded:GetInterface(string name, bool ignoreCase) When overridden in a derived class, searches for the specified interface, specifying whether to do a case-sensitive search. |
| GetInterfaceMap | Returns an interface mapping for the specified interface type. |
| GetInterfaces | When overridden in a derived class, gets all the interfaces implemented or inherited by the current Type. |
| GetMember | Overloaded:GetMember(string name) Searches for the members with the specified name. |
| GetMember | Overloaded:GetMember(string name, BindingFlags bindingAttr) Searches for the specified members, using the specified binding constraints. |
| GetMember | Overloaded:GetMember(string name, MemberTypes type, BindingFlags bindingAttr) Searches for the specified members of the specified member type, using the specified binding constraints. |
| GetMembers | Overloaded:GetMembers() Returns all the public members of the current Type. |
| GetMembers | Overloaded:GetMembers(BindingFlags bindingAttr) When overridden in a derived class, searches for the members defined for the current Type, using the specified binding constraints. |
| GetMethod | Overloaded:GetMethod(string name) Searches for the public method with the specified name. |
| GetMethod | Overloaded:GetMethod(string name, BindingFlags bindingAttr) Searches for the specified method, using the specified binding constraints. |
| GetMethod | Overloaded:GetMethod(string name, Type[] types) Searches for the specified public method whose parameters match the specified argument types. |
| GetMethod | Overloaded:GetMethod(string name, Type[] types, ParameterModifier[] modifiers) Searches for the specified public method whose parameters match the specified argument types and modifiers. |
| GetMethod | Overloaded:GetMethod(string name, BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers) Searches for the specified method whose parameters match the specified argument types and modifiers, using the specified binding constraints. |
| GetMethod | Overloaded:GetMethod(string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) Searches for the specified method whose parameters match the specified argument types and modifiers, using the specified binding constraints and the specified calling convention. |
| GetMethods | Overloaded:GetMethods() Returns all the public methods of the current Type. |
| GetMethods | Overloaded:GetMethods(BindingFlags bindingAttr) When overridden in a derived class, searches for the methods defined for the current Type, using the specified binding constraints. |
| GetNestedType | Overloaded:GetNestedType(string name) Searches for the nested type with the specified name. |
| GetNestedType | Overloaded:GetNestedType(string name, BindingFlags bindingAttr) When overridden in a derived class, searches for the specified nested type, using the specified binding constraints. |
| GetNestedTypes | Overloaded:GetNestedTypes() Returns all the types nested within the current Type. |
| GetNestedTypes | Overloaded:GetNestedTypes(BindingFlags bindingAttr) When overridden in a derived class, searches for the types nested within the current Type, using the specified binding constraints. |
| GetProperties | Overloaded:GetProperties() Returns all the public properties of the current Type. |
| GetProperties | Overloaded:GetProperties(BindingFlags bindingAttr) When overridden in a derived class, searches for the properties of the current Type, using the specified binding constraints. |
| GetProperty | Overloaded:GetProperty(string name) Searches for the public property with the specified name. |
| GetProperty | Overloaded:GetProperty(string name, BindingFlags bindingAttr) Searches for the specified property, using the specified binding constraints. |
| GetProperty | Overloaded:GetProperty(string name, Type returnType) Searches for the public property with the specified name and return type. |
| GetProperty | Overloaded:GetProperty(string name, Type[] types) Searches for the specified public property whose parameters match the specified argument types. |
| GetProperty | Overloaded:GetProperty(string name, Type returnType, Type[] types) Searches for the specified public property whose parameters match the specified argument types. |
| GetProperty | Overloaded:GetProperty(string name, Type returnType, Type[] types, ParameterModifier[] modifiers) Searches for the specified public property whose parameters match the specified argument types and modifiers. |
| GetProperty | Overloaded:GetProperty(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) Searches for the specified property whose parameters match the specified argument types and modifiers, using the specified binding constraints. |
| GetType (inherited from System.Object) |
Overloaded:GetType()See base class member description: System.Object.GetTypeDerived from System.Object, the primary base class for all objects. |
| GetType | Overloaded:GetType(string typeName) Gets the Type with the specified name, performing a case-sensitive search. |
| GetType | Overloaded:GetType(string typeName, bool throwOnError) Gets the Type with the specified name, performing a case-sensitive search and specifying whether to throw an exception if an error occurs while loading the Type. |
| GetType | Overloaded:GetType(string typeName, bool throwOnError, bool ignoreCase) Gets the Type with the specified name, specifying whether to perform a case-sensitive search and whether to throw an exception if an error occurs while loading the Type. |
| GetTypeArray | Gets the types of the objects in the specified array. |
| GetTypeCode | Gets the underlying type code of the specified Type. |
| GetTypeFromHandle | Gets the Type referenced by the specified type handle. |
| GetTypeHandle | Gets the handle for the Type of a specified object. |
| InvokeMember | Overloaded:InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args) Invokes the specified member, using the specified binding constraints and matching the specified argument list. |
| InvokeMember | Overloaded:InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, CultureInfo culture) Invokes the specified member, using the specified binding constraints and matching the specified argument list and culture. |
| InvokeMember | Overloaded:InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters) When overridden in a derived class, invokes the specified member, using the specified binding constraints and matching the specified argument list, modifiers and culture. |
| IsAssignableFrom | Determines whether an instance of the current Type can be assigned from an instance of the specified Type. |
| IsDefined (inherited from System.Reflection.MemberInfo) |
See base class member description: System.Reflection.MemberInfo.IsDefined When overridden in a derived class, indicates whether one or more instance of attributeType is defined on this member. |
| IsInstanceOfType | Determines whether the specified object is an instance of the current Type. |
| IsSubclassOf | Determines whether the current Type derives from the specified Type. |
| ToString | Overridden: Returns a String representing the name of the current Type. |
| ctor #1 | Default constructor. This constructor is called by derived class constructors to initialize state in this type. Initializes a new instance of the Type class. |
| Finalize (inherited from System.Object) |
See base class member description: System.Object.Finalize Derived from System.Object, the primary base class for all objects. |
| GetAttributeFlagsImpl | When overridden in a derived class, implements the Type.Attributes property and gets a bitmask indicating the attributes associated with the Type. |
| GetConstructorImpl | When overridden in a derived class, searches for a constructor whose parameters match the specified argument types and modifiers, using the specified binding constraints and the specified calling convention. |
| GetMethodImpl | When overridden in a derived class, searches for the specified method whose parameters match the specified argument types and modifiers, using the specified binding constraints and the specified calling convention. |
| GetPropertyImpl | When overridden in a derived class, searches for the specified property whose parameters match the specified argument types and modifiers, using the specified binding constraints. |
| HasElementTypeImpl | When overridden in a derived class, implements the Type.HasElementType property and determines whether the current Type encompasses or refers to another type; that is, whether the current Type is an array, a pointer, or is passed by reference. |
| IsArrayImpl | When overridden in a derived class, implements the Type.IsArray property and determines whether the Type is an array. |
| IsByRefImpl | When overridden in a derived class, implements the Type.IsByRef property and determines whether the Type is passed by reference. |
| IsCOMObjectImpl | When overridden in a derived class, implements the Type.IsCOMObject property and determines whether the Type is a COM object. |
| IsContextfulImpl | Implements the Type.IsContextful property and determines whether the Type can be hosted in a context. |
| IsMarshalByRefImpl | Implements the Type.IsMarshalByRef property and determines whether the Type is marshalled by reference. |
| IsPointerImpl | When overridden in a derived class, implements the Type.IsPointer property and determines whether the Type is a pointer. |
| IsPrimitiveImpl | When overridden in a derived class, implements the Type.IsPrimitive property and determines whether the Type is one of the primitive types. |
| IsValueTypeImpl | Implements the Type.IsValueType property and determines whether the Type is a value type; that is, not a class or an interface. |
| MemberwiseClone (inherited from System.Object) |
See base class member description: System.Object.MemberwiseClone Derived from System.Object, the primary base class for all objects. |
Hierarchy:
protected Type(); |
public static readonly char Delimiter;
|
typeNameSpace + Type.Delimiter + baseName + '.' + cultureName [+ '-' + subCultureName] + '.resources'
public static readonly Type[] EmptyTypes;
|
cInfo = type.GetConstructor (BindingFlags.ExactBinding, null,
Type.EmptyTypes, null);
public static readonly MemberFilter FilterAttribute;
|
For example, the Object can be assigned the value of a field from FieldAttributes such as Public. In that case, when the FilterAttribute delegate is invoked, it will return true only if the method represented by the MemberInfo object is decorated with the public field attribute in metadata.
using System;
using System.Reflection;
using System.Security;
public class MyFilterAttributeSample
{
public static void Main()
{
try
{
MemberFilter myFilter = Type.FilterAttribute;
Type myType = typeof(System.String);
MemberInfo[] myMemberInfoArray = myType.FindMembers(MemberTypes.Constructor
|MemberTypes.Method, BindingFlags.Public | BindingFlags.Static |
BindingFlags.Instance, myFilter, MethodAttributes.SpecialName);
foreach (MemberInfo myMemberinfo in myMemberInfoArray)
{
Console.Write ("\n" + myMemberinfo.Name);
Console.Write (" is a " + myMemberinfo.MemberType.ToString());
}
}
catch(ArgumentNullException e)
{
Console.Write("ArgumentNullException : " + e.Message);
}
catch(SecurityException e)
{
Console.Write("SecurityException : " + e.Message);
}
catch(Exception e)
{
Console.Write("Exception :" + e.Message);
}
}
}
public static readonly MemberFilter FilterName;
|
For example, the Object may be assigned the value "Byte*". In that case, when the FilterName delegate is invoked, it will return true only if the method represented by the MemberInfo object has a name that begins with "Byte".
// Get the set of methods associated with the type
MemberInfo[] mi = typeof(Application).FindMembers(MemberTypes.Constructor |
MemberTypes.Method,
BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.DeclaredOnly,
Type.FilterName, "*");
Console.WriteLine("Number of methods (includes constructors): " + mi.Length);
public static readonly MemberFilter FilterNameIgnoreCase;
|
For example, the Object may be assigned the value "ByTe*". In that case, when the FilterName delegate is invoked, it will return true only if the method represented by the MemberInfo object has a name that begins with "byte", ignoring case.
using System;
using System.Reflection;
using System.Security;
public class MyFilterNameIgnoreCaseSample
{
public static void Main()
{
try
{
MemberFilter myFilter = Type.FilterNameIgnoreCase;
Type myType = typeof(System.String);
MemberInfo[] myMemberinfo1 = myType.FindMembers(MemberTypes.Constructor
|MemberTypes.Method, BindingFlags.Public | BindingFlags.Static |
BindingFlags.Instance, myFilter, "C*");
foreach (MemberInfo myMemberinfo2 in myMemberinfo1)
{
Console.Write("\n" + myMemberinfo2.Name);
MemberTypes Mymembertypes = myMemberinfo2.MemberType;
Console.WriteLine(" is a " + Mymembertypes.ToString());
}
}
catch(ArgumentNullException e)
{
Console.Write("ArgumentNullException : " + e.Message);
}
catch(SecurityException e)
{
Console.Write("SecurityException : " + e.Message);
}
catch(Exception e)
{
Console.Write("Exception : " + e.Message);
}
}
}
public static readonly object Missing;
|
This code produces the following output:
a = 10 b = 55.3 c = 12
a = 10 b = 1.3 c = 1
a = 10 b = 1.2 c = 1
public abstract Assembly Assembly {get;}
|
using System;
using System.Reflection;
class MyAssemblyClass
{
public static void Main()
{
Type objType = typeof(System.Array);
// Print the assembly Fullname.
Console.WriteLine ("Assembly Fullname -\t" + objType.Assembly.FullName.ToString() + "\n" );
// Print the assembly Qualified Name.
Console.WriteLine ("Assembly Qualified name -\t" + objType.AssemblyQualifiedName.ToString());
}
}
public abstract string AssemblyQualifiedName {get;}
|
| Delimiter | Meaning |
|---|---|
| Backslash (\) | Escape character. |
| Comma (,) | Precedes the Assembly name. |
| Plus sign (+) | Precedes a nested class. |
| Period (.) | Denotes namespace identifiers. |
For example, the fully qualified name for a class might look like this:
TopNamespace.SubNameSpace.ContainingClass+NestedClass,MyAssembly
If the namespace were TopNamespace.Sub+Namespace, then the string would have to precede the plus sign (+) with an escape character (\) to prevent it from being interpreted as a nesting separator. Reflection emits this string as follows:
TopNamespace.Sub\+Namespace.ContainingClass+NestedClass,MyAssembly
A "++" becomes "\+\+", and a "\" becomes "\\".
This qualified name can be persisted and later used to load the Type. To search for and load a Type, use Type.GetType either with the type name only or with the assembly qualified type name. Type.GetType with the type name only will look for the Type in the caller's assembly and then in the System assembly. Type.GetType with the assembly qualified type name will look for the Type in any assembly.
Type names may include trailing characters that denote additional information about the type, such as whether the type is a reference type, a pointer type or an array type. To retrieve the type name without these trailing characters, use
t.GetElementType().ToString()
, where t is the type.
Spaces are relevant in all type name components except the assembly name. In the assembly name, spaces before the ',' separator are relevant, but spaces after the ',' separator are ignored.
using System;
using System.Reflection;
class MyAssemblyClass
{
public static void Main()
{
Type objType = typeof(System.Array);
// Print the assembly Fullname.
Console.WriteLine ("Assembly Fullname -\t" + objType.Assembly.FullName.ToString() + "\n" );
// Print the assembly Qualified Name.
Console.WriteLine ("Assembly Qualified name -\t" + objType.AssemblyQualifiedName.ToString());
}
}
public TypeAttributes Attributes {get;}
|
public abstract Type BaseType {get;}
|
Interfaces inherit from Object and from zero or more base interfaces; therefore, the base type of an interface is considered to be Object. The base interfaces can be determined with Type.GetInterfaces or Type.FindInterfaces.
This property is read-only.
using System;
class TestType
{
public static void Main()
{
Type t = typeof(int);
Console.WriteLine("{0} inherits from {1}", t,t.BaseType);
}
}
This code produces the following output:
System.Int32 inherits from System.ValueType
public override Type DeclaringType {get;}
|
using System;
using System.Reflection;
public abstract class dtype {
public abstract class MyClassA {
public abstract int m();
}
public abstract class MyClassB : MyClassA {
}
public static void Main(string[] args) {
Console.WriteLine("Declaring type of m is {0}",
typeof(MyClassB).GetMethod("m").DeclaringType);
}
}
This code produces the following output:
Declaring type of m is dtype+MyClassA
public static Binder DefaultBinder {get;}
|
The general principle is that Binder.ChangeType should perform only widening coercions, which never lose data. An example of a widening coercion is coercing a value that is a 32-bit signed integer to a value that is a 64-bit signed integer. This is distinguished from a narrowing coercion, which may lose data. An example of a narrowing coercion is coercing a 64-bit signed integer to a 32-bit signed integer.
The following table lists the coercions performed by the default ChangeType.
| Source Type | Target Type |
|---|---|
| Any type | Its base type. |
| Any type | The interface it implements. |
| Char | Unt16, UInt32, Int32, UInt64, Int64, Single, Double |
| Byte | Char, Unt16, Int16, UInt32, Int32, UInt64, Int64, Single, Double |
| SByte | Int16, Int32, Int64, Single, Double |
| UInt16 | UInt32, Int32, UInt64, Int64, Single, Double |
| Int16 | Int32, Int64, Single, Double |
| UInt32 | UInt64, Int64, Single, Double |
| Int32 | Int64, Single, Double |
| UInt64 | Single, Double |
| Int64 | Single, Double |
| Single | Double |
| Non-reference | By-reference. |
using System;
using System.Reflection;
public class MyDefaultBinderSample
{
public static void Main()
{
try
{
Binder defaultBinder = Type.DefaultBinder;
MyClass myClass = new MyClass();
// Invoke HelloWorld method of Myclass.
myClass.GetType().InvokeMember("HelloWorld", BindingFlags.InvokeMethod,
defaultBinder, myClass, new object [] {});
}
catch(Exception e)
{
Console.WriteLine("Exception :" + e.Message);
}
}
class MyClass
{
public void HelloWorld()
{
Console.WriteLine("Hello World");
}
}
}
public abstract string FullName {get;}
|
This property is read-only.
using System;
class TestFullName
{
public static void Main()
{
Type t = typeof(Array);
Console.WriteLine("Full name of Array type is {0}",t.FullName);
}
}
This code produces the following output:
Full name of Array type is
System.Array
public abstract Guid GUID {get;}
|
// Get the type corresponding to the class 'MyClass'.
Type myType = typeof(MyClass1);
// Get the object of the 'Guid'.
Guid myGuid =(Guid) myType.GUID;
Console.WriteLine("The Name of the Class is :"+myType.ToString());
Console.WriteLine("The ClassId of the 'MyClass' is :"+myType.GUID);
public bool HasElementType {get;}
|
public class MyClass
{
}
public class Type_HasElementType
{
public static void Main()
{
try
{
// An non array or pointer or reference element.
MyClass myObject1 = new MyClass();
Object myObject2 = myObject1 ;
// An object of array type.
MyClass[] myObject3 = new MyClass[5];
Object myObject4 = myObject3 ;
Object[] myObjects = new Object[] { myObject1, myObject2, myObject3, myObject4 };
Console.WriteLine("\nCheck whether the object refers to array or pointer or reference type.\n");
for(int i = 0; i < myObjects.Length; i++)
{
if(myObjects[i].GetType().HasElementType)
Console.WriteLine("'myObject{0}' refers to an array or pointer or reference", i);
else
Console.WriteLine("'myObject{0}' does not refer to an array or pointer or reference", i);
}
}
catch( Exception e )
{
Console.WriteLine( "Exception: {0} \n", e.Message ) ;
}
}
}
public bool IsAbstract {get;}
|
public abstract class MyAbstractClass
{
}
public class MyClass
{
}
public class Type_IsAbstract
{
public static void Main()
{
try
{
Console.WriteLine("\nChecking whether the type is abstract\n");
// Check whether the return Type is abstract or not.
Console.WriteLine("'MyAbstractClass' is {0}",
(typeof(MyAbstractClass).IsAbstract) ?
"an abstract class" :
"not an abstract class" );
// Check whether the return Type is abstract or not.
Console.WriteLine("'MyClass' is {0}",
(typeof(MyClass).IsAbstract) ?
"an abstract class" :
"not an abstract class" );
}
catch( Exception e )
{
Console.WriteLine( "Exception: {0} \n", e.Message );
}
}
}
public bool IsAnsiClass {get;}
|
public class MyClass
{
protected string myField = "A sample protected field" ;
}
public class MyType_IsAnsiClass
{
public static void Main()
{
try
{
MyClass myObject = new MyClass();
// Get the type of the 'MyClass'.
Type myType = typeof(MyClass);
// Get the field information and the attributes associated with 'MyClass'.
FieldInfo myFieldInfo = myType.GetField("myField",
BindingFlags.NonPublic|BindingFlags.Instance);
Console.WriteLine( "\nChecking for AnsiClass attribute for a field\n");
// Get and display the name, field, and the AnsiClass attribute.
Console.WriteLine("Name of Class: {0} \nValue of Field: {1} \nIsAnsiClass = {2}",
myType.FullName, myFieldInfo.GetValue(myObject),
myType.IsAnsiClass);
}
catch(Exception e)
{
Console.WriteLine("Exception : {0}",e.Message);
}
}
}
public bool IsArray {get;}
|
This property is read-only.
using System;
class TestIsArray
{
public static void Main()
{
int [] array = {1,2,3,4};
Type at = typeof(Array);
Type t = array.GetType();
Console.WriteLine("Type is {0}. IsArray? {1}", at, at.IsArray);
Console.WriteLine("Type is {0}. IsArray? {1}", t, t.IsArray);
}
}
This code produces the following output:
Type is System.Array. IsArray? False
Type is System.Int32[]. IsArray? True
public bool IsAutoClass {get;}
|
public bool IsAutoLayout {get;}
|
Use the AutoLayout attribute to let the runtime engine decide the best way to layout the objects of the class. Classes marked with the AutoLayout attribute indicate that the loader will choose the appropriate way to lay out the class; any layout information that may have been specified is ignored.
// The MyDemoAttribute class is selected as AutoLayout.
[StructLayoutAttribute(LayoutKind.Auto)]
public class MyDemoAttribute
{
}
public class MyTypeClass
{
public static void Main(string[] args)
{
MyAutoLayoutMethod("MyDemoAttribute");
}
public static void MyAutoLayoutMethod(string typeName)
{
try
{
// Create an object of 'Type' class using the 'GetType' method.
Type myType=Type.GetType(typeName);
// Get and display the 'IsAutoLayout' property of the
// 'MyDemoAttribute' instance.
Console.WriteLine("\n The 'Autolayout' property for the 'MyDemoAttribute' is: {0}.",myType.IsAutoLayout);
}
catch(Exception e)
{
Console.WriteLine("\nThe following exception is raised: {0}." ,e.Message);
}
}
}
public bool IsByRef {get;}
|
public bool IsClass {get;}
|
The TypeAttributes.ClassSemanticsMask distinguishes a type declaration as class, interface, or value type.
This property is read-only.
public class MyDemoClass
{
}
public class MyTypeClass
{
public static void Main(string[] args)
{
try
{
Type myType=Type.GetType("MyDemoClass");
// Get and display the 'IsClass' property of the 'MyDemoClass' instance.
Console.WriteLine("\n'MyDemoClass' is of type 'Class': {0}.", myType.IsClass);
}
catch(Exception e)
{
Console.WriteLine("\nThe following exception is raised: {0}." ,e.Message);
}
}
}
public bool IsCOMObject {get;}
|
You can also load a COM class and get a Type object for that COM class by using the tool.
public bool IsContextful {get;}
|
public class MyContextBoundClass: ContextBoundObject
{
public string myString = "This class demonstrates the isContextful and isMarshalByRef properties.";
}
public class MyTypeDemoClass
{
public static void Main()
{
try
{
// Check if the types can be hosted in a Context.
Console.WriteLine ("The Contextful property for the '{0}' type is: {1}", typeof(MyTypeDemoClass).Name, typeof(MyTypeDemoClass).IsContextful);
Console.WriteLine ("The Contextful property for the '{0}' type is: {1}", typeof(MyContextBoundClass).Name, typeof(MyContextBoundClass).IsContextful);
// Check if the types are marshalled by reference.
Console.WriteLine ("The MarshalByRef property of '{0}' is: {1} ", typeof(MyTypeDemoClass).Name, typeof(MyTypeDemoClass).IsMarshalByRef);
Console.WriteLine ("The MarshalByRef property of '{0}' is: {1} ", typeof(MyContextBoundClass).Name, typeof(MyContextBoundClass).IsMarshalByRef);
// Check if the types are primitive datatypes.
Console.WriteLine ("'{0}' is a primitive datatype : {1} ", typeof(int).Name, typeof(int).IsPrimitive);
Console.WriteLine ("'{0}' is a primitive datatype : {1} ", typeof(string).Name, typeof(string).IsPrimitive);
}
catch (Exception e)
{
Console.WriteLine("The following exception is raised : " + e.Message);
}
}
}
public bool IsEnum {get;}
|
This property is read-only.
using System;
public enum Color
{
Red, Blue, Green
}
class TestIsEnum
{
public static void Main()
{
Type colorType = typeof(Color);
Type enumType = typeof(Enum);
Console.WriteLine("Color is enum? {0}", colorType.IsEnum);
Console.WriteLine("Color is valueType? {0}", colorType.IsValueType);
Console.WriteLine("Enum is enum Type? {0}", enumType.IsEnum);
Console.WriteLine("Enum is value? {0}", enumType.IsValueType);
}
}
This code produces the following output:
Color is enum? True
Color is valueType? True
Enum is enum Type? False
Enum is value? False
public bool IsExplicitLayout {get;}
|
Classes marked with the ExplicitLayout attribute cause the loader to ignore field sequence and to use the explicit layout rules provided, in the form of field offsets, overall class size and alignment, or all of these.
Use the ExplicitLayout attribute to specify the offsets at which each field starts, or to specify the overall size and, optionally, the packing size of the objects of the class. The packing size is the empty memory space between fields and must be 1, 2, 4, 8 or 16 bytes.
//The class is selected for the ExplicitLayout.
[StructLayoutAttribute(LayoutKind.Explicit)]
public class MyDemoAttribute
{
}
public class MyTypeClass
{
public static void Main(string[] args)
{
MyIsExplicitLayoutMethod("MyDemoAttribute");
}
public static void MyIsExplicitLayoutMethod(string typeName)
{
try
{
// Create an object of 'Type' class using the 'GetType' method.
Type myType=Type.GetType(typeName);
// Get and display the 'IsExplicitLayout' property.
Console.WriteLine("\n'MyDemoAttribute' instance's 'IsExplicitLayout' property is: {0}.",myType.IsExplicitLayout);
}
catch(Exception e)
{
Console.WriteLine("\nThe following exception is raised: {0}." ,e.Message);
}
}
}
public bool IsImport {get;}
|
public bool IsInterface {get;}
|
This property is read-only.
// Interface declaration.
interface myIFace
{
}
class MyIsInterface
{
public static void Main(string []args)
{
try
{
// Get the attribute IsInterface for myIFace.
bool myBool1 = typeof(myIFace).IsInterface;
//Display the IsInterface attribute for myIFace.
Console.WriteLine("The type mentioned is an interface: {0}",myBool1);
// Get the attribute IsInterface for MyIsInterface.
bool myBool2 = typeof(MyIsInterface).IsInterface;
//Display the IsInterface attribute for MyIsInterface.
Console.WriteLine("The type mentioned is an interface: {0}",myBool2);
}
catch(Exception e)
{
Console.WriteLine("\nThe following exception is raised : {0}",e.Message);
}
}
}
public bool IsLayoutSequential {get;}
|
Classes marked with the SequentialLayout attribute guides the loader to preserve field order as emitted, but otherwise the specific offsets are calculated based on the common language runtime type of the field; these may be shifted by explicit offset, padding, or alignment information.
Use the SequentialLayout attribute to layout the objects of the class sequentially and to specify the packing size between adjacent fields. The packing size is the empty memory space between fields and must be 1, 2, 4, 8 or 16 bytes. A field will be aligned to its natural size or to the packing size, whichever results in a smaller offset.
// MyTypeSequential1 class declaration.
class MyTypeSequential1
{
}
[StructLayoutAttribute(LayoutKind.Sequential)]
class MyTypeSequential2
{
public static void Main(string []args)
{
try
{
// Create an instance of 'myTypeSeq1' class.
MyTypeSequential1 myObj1 = new MyTypeSequential1();
Type myTypeObj1 = myObj1.GetType();
// Check and displays the attribute 'SequentialLayout'.
Console.WriteLine("\nThe object myObj1 has 'IsLayoutSequential': {0}", myObj1.GetType().IsLayoutSequential);
// Create an instance of 'myTypeSeq2' class.
MyTypeSequential2 myObj2 = new MyTypeSequential2();
Type myTypeObj2 = myObj2.GetType();
// Check and displays the attribute 'SequentialLayout'.
Console.WriteLine("\nThe object myObj2 has 'IsLayoutSequential': {0}", myObj2.GetType().IsLayoutSequential);
}
catch(Exception e)
{
Console.WriteLine("\nThe following exception is raised: {0}",e.Message);
}
}
}
public bool IsMarshalByRef {get;}
|
public class MyContextBoundClass: ContextBoundObject
{
public string myString = "This class demonstrates the isContextful and isMarshalByRef properties.";
}
public class MyTypeDemoClass
{
public static void Main()
{
try
{
// Check if the types can be hosted in a Context.
Console.WriteLine ("The Contextful property for the '{0}' type is: {1}", typeof(MyTypeDemoClass).Name, typeof(MyTypeDemoClass).IsContextful);
Console.WriteLine ("The Contextful property for the '{0}' type is: {1}", typeof(MyContextBoundClass).Name, typeof(MyContextBoundClass).IsContextful);
// Check if the types are marshalled by reference.
Console.WriteLine ("The MarshalByRef property of '{0}' is: {1} ", typeof(MyTypeDemoClass).Name, typeof(MyTypeDemoClass).IsMarshalByRef);
Console.WriteLine ("The MarshalByRef property of '{0}' is: {1} ", typeof(MyContextBoundClass).Name, typeof(MyContextBoundClass).IsMarshalByRef);
// Check if the types are primitive datatypes.
Console.WriteLine ("'{0}' is a primitive datatype : {1} ", typeof(int).Name, typeof(int).IsPrimitive);
Console.WriteLine ("'{0}' is a primitive datatype : {1} ", typeof(string).Name, typeof(string).IsPrimitive);
}
catch (Exception e)
{
Console.WriteLine("The following exception is raised : " + e.Message);
}
}
}
public bool IsNestedAssembly {get;}
|
// Enclose a class.
class MyClassA
{
// Internal nested class.
internal class MyClassB
{
}
}
class MyTestClass
{
public static void Main(string[] args)
{
// Get the Type of the nested class.
Type myTypeB = typeof(MyClassA.MyClassB);
// Get the 'IsNestedAssembly' property of the nested class
// 'Type'.
Console.WriteLine("\nThe nested class has the property 'IsNestedAssembly' value: "+
myTypeB.IsNestedAssembly.ToString());
}
}
public bool IsNestedFamANDAssem {get;}
|
A Type object's family is defined as all objects of the exact same Type and of its subtypes.
public bool IsNestedFamily {get;}
|
A Type object's family is defined as all objects of the exact same Type and of its subtypes.
// Enclose a class.
class MyClassA
{
// Protected nested class.
protected class MyClassB
{
}
}
class MyTestClass : MyClassA
{
public static void Main(string[] args)
{
// Get the Type of the nested class.
Type myTypeB = typeof(MyClassA.MyClassB);
// Get the 'IsNestedFamily' property the of the nested class
// 'Type'.
Console.WriteLine("\nThe nested class has the property 'IsNestedFamily' value: "+
myTypeB.IsNestedFamily.ToString());
}
}
public bool IsNestedFamORAssem {get;}
|
A Type object's family is defined as all objects of the exact same Type and of its subtypes.
// Enclose a class.
class MyClassA
{
// Protected internal nested class.
protected internal class MyClassB
{
}
}
class MyTestClass
{
public static void Main(string[] args)
{
// Get the Type of the nested class.
Type myTypeB = typeof(MyClassA.MyClassB);
// Get the 'IsNestedFamORAssem' property of the nested class
// 'Type'.
Console.WriteLine("\nThe nested class has the property 'IsNestedFamORAssem' value: "+
myTypeB.IsNestedFamORAssem.ToString());
}
}
public bool IsNestedPrivate {get;}
|
// Outer class.
public class MyClassA
{
// Private nested class.
private class MyClassB
{
}
public static void Main(string[] args)
{
// Get the Type of the nested class.
Type myTypeB = typeof(MyClassA.MyClassB);
// Get the 'IsNestedPrivate' property of the nested class 'Type'.
Console.WriteLine("\nThe nested class has the property 'IsNestedPrivate'value: "+
myTypeB.IsNestedPrivate.ToString());
}
}
public bool IsNestedPublic {get;}
|
using System;
// Enclose a class.
public class MyClassA
{
// Public nested class.
public class MyClassB
{
}
public static void Main(string[] args)
{
// Get the Type of the nested class.
Type myTypeB = typeof(MyClassA.MyClassB);
// Get the 'IsNestedPublic' property of the nested class
// 'Type'.
Console.WriteLine("\nThe nested class has the property 'IsNestedPublic' value: "+
myTypeB.IsNestedPublic.ToString());
}
}
public bool IsNotPublic {get;}
|
TypeAttributes.VisibilityMask selects the visibility attributes.
using System;
using System.IO;
using System.Reflection;
class MyMemberInfo {
public static void Main(string[] args) {
Console.WriteLine ("\nReflection.MemberInfo");
//Get the Type and MemberInfo
Type MyType =Type.GetType("System.IO.File");
MemberInfo[] Mymemberinfoarray = MyType.GetMembers();
//Get and display the DeclaringType method
Console.WriteLine("\nThere are {0} members in {1}.",
Mymemberinfoarray.Length, MyType.FullName);
Console.WriteLine("Is {0} public? {1}", MyType.FullName,
MyType.IsPublic.ToString());
}
}
This code produces the following output:
There are 27 members in System.IO.File.
Is System.IO.File public? False
The following code example demonstrates why you cannot use IsPublic and IsNotPublic for nested classes.
public class A {
public class B { }
private class C { }
}
For nested classes, ignore the results of IsPublic and IsNotPublic and pay attention only to the results of IsNestedPublic and IsNestedPrivate. The reflection output for this code fragment would be as follows:
| Class | IsNotPublic | IsPublic | IsNestedPublic |
|---|