Partager via


Reflection (C# Programming Guide) 

Reflection provides objects (of type Type) that encapsulate 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 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:
int i = 42;
System.Type type = i.GetType();
System.Console.WriteLine(type);

The output is:

System.Int32

In this example, Reflection is used to obtain the full name of a loaded assembly:

// Using Reflection to get information from an Assembly:
System.Reflection.Assembly o = System.Reflection.Assembly.Load("mscorlib.dll");
System.Console.WriteLine(o.GetName());

The output is:

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

Reflection Overview

Reflection is useful in the following situations:

For more information:

C# Language Specification

For more information, see the following sections in the C# Language Specification:

  • 1.12 Attributes

  • 7.5.11 The typeof operator

See Also

Reference

Application Domains (C# Programming Guide)

Concepts

C# Programming Guide
Assemblies and the Global Assembly Cache (C# Programming Guide)