What is Reflection in .NET?

It extends the benefits of metadata by allowing developers to inspect and use it at runtime. For example, dynamically determine all the classes contained in a given assembly and invoke their methods. Reflection provides objects 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. You can then invoke the type’s methods or access its fields and properties. Namespace: System.Reflection
All .NET compilers produce metadata about the types defined in the modules they produce. This metadata is packaged along with the module (modules in turn are packaged together in assemblies), and can be accessed by a mechanism called reflection. The System.Reflection namespace contains classes that can be used to interrogate the types for a module/assembly.
Using reflection to access .NET metadata is very similar to using ITypeLib/ITypeInfo to access type library data in COM, and it is used for similar purposes – e.g. determining data type sizes for marshaling data across context/process/machine boundaries.
Reflection can also be used to dynamically invoke methods (see System.Type.InvokeMember ) , or even create types dynamically at run-time (see System.Reflection.Emit.TypeBuilder).
For example, if you want to programmatically display all the methods of a class, you could do it like so:

using System;
using System.Reflection;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var t = typeof(MyClass);
foreach (var m in t.GetMethods())
{
Console.WriteLine(m.Name);
}
Console.ReadLine();
}
}
public class MyClass
{
public int Add(int x, int y)
{
return x + y;
}
public int Subtract(int x, int y)
{
return x - y;
}
}
}

Tagged , . Bookmark the permalink.

Leave a Reply