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.
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);
System.Int32
// Using Reflection to get information from an Assembly:
System.Reflection.Assembly info = typeof(System.Int32).Assembly;
System.Console.WriteLine(info);
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
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.
- When you have to access attributes in your program’s metadata. See the topic [Accessing Attributes With Reflection](https://msdn.microsoft.com/en-us/library/z919e8tw(v=vs.90).aspx).(It allows view attribute information at runtime.)
- For examining and instantiating types in an assembly.(It allows examining various types in an assembly and instantiate these types.)
- For building new types at runtime. Use classes in System.Reflection.Emit. (It allows creating new types at runtime and then performs some tasks using those types.)
- For performing late binding, accessing methods on types created at run time. See the topic Dynamically Loading and Using Types.(It allows late binding to methods and properties)
Leave a Reply