Dela via


Reflection (C# and Visual Basic)

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 Extending Metadata Using Attributes.

Here's a simple example of reflection using the static method GetType - inherited by all types from the Object base class - to obtain the type of a variable:

' Using GetType to obtain type information: 
Dim i As Integer = 42
Dim type As System.Type = i.GetType()
System.Console.WriteLine(type)
// Using GetType to obtain type information: 
int i = 42;
System.Type type = i.GetType();
System.Console.WriteLine(type);

The output is:

System.Int32

The following example uses reflection to obtain the full name of the loaded assembly.

' Using Reflection to get information from an Assembly: 
Dim info As System.Reflection.Assembly = GetType(System.Int32).Assembly
System.Console.WriteLine(info)
// Using Reflection to get information from an Assembly:
System.Reflection.Assembly info = typeof(System.Int32).Assembly;
System.Console.WriteLine(info);

The output is:

mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

Note

The C# keywords protected and internal have no meaning in 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 Overview

Reflection is useful in the following situations:

For more information:

See Also

Concepts

C# Programming Guide

Other Resources

Visual Basic Programming Guide

Application Domains (C# and Visual Basic)

Assemblies in the Common Language Runtime