Reflection provides objects (of type Type) that describe assemblies, modules, and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties. If you are using attributes in your code, reflection enables you to access them. For more information, see Attributes.
Here's a simple example of reflection using the GetType() method - inherited by all types from the
Object base class - to obtain the type of a variable:
Make sure you add
using System; and
using System.Reflection; at the top of your .cs file.
// Using GetType to obtain type information: int i = 42; Type type = i.GetType(); Console.WriteLine(type);
The output is:
The following example uses reflection to obtain the full name of the loaded assembly.
// Using Reflection to get information of an Assembly: Assembly info = typeof(int).Assembly; Console.WriteLine(info);
The output is:
System.Private.CoreLib, Version=184.108.40.206, Culture=neutral, PublicKeyToken=7cec85d7bea7798e.
The C# keywords
internal have no meaning in Intermediate Language (IL) and are not used in the reflection APIs. The corresponding terms in IL are Family and Assembly. To identify an
internal method using reflection, use the IsAssembly property. To identify a
protected internal method, use the IsFamilyOrAssembly.
Reflection is useful in the following situations:
- When you have to access attributes in your program's metadata. For more information, see Retrieving Information Stored in Attributes.
- For examining and instantiating types in an assembly.
- For building new types at run time. Use classes in System.Reflection.Emit.
- For performing late binding, accessing methods on types created at run time. See the topic Dynamically Loading and Using Types.
For more information:
- Viewing Type Information
- Reflection and Generic Types
- Retrieving Information Stored in Attributes