SiteMap  | About    

What is .Net Reflection

Reflection ?


In .Net, during the compile time Metadata created with MSIL and stored it in a file called a Manifest . Both Metadata and Microsoft Intermediate Language together wrapped in a Portable Executable (PE) file and this can be accessed at runtime by a mechanism, called Reflection.

At runtime, the Reflection mechanism uses the Portable Executable file to read information about the assembly and it is possible to uncover the methods, properties, and events of a type, and to invoke them dynamically. Reflection generally begins with a call to a method present on every object in the .NET framework, GetType(). The GetType() is a member of the System.Object class, and the method returns an instance of System.Type.

Type type = refCls.GetType();

The classes in the System.Reflection namespace, together with Type, enable you to get information about loaded assemblies and the types defined within them, such as classes, interfaces, and value types.

The following program demonstrate a sample code where we are accessing at run time through methods and function of a Class "testClass".

C# Source Code

using System; using System.Reflection; using System.Windows.Forms; namespace WindowsFormsApplication1 { public class testClass { int result; public testClass() { } public int addNum(int x, int y) { result = x + y; return result; } } public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { testClass refCls = new testClass(); Type type = refCls.GetType(); foreach (MemberInfo refInfo in type.GetMembers()) { MessageBox.Show(refInfo.Name); } } } }

VB.Net Source Code

Imports System.Reflection Public Class testClass Private result As Integer Public Sub New() End Sub Public Function addNum(ByVal x As Integer, ByVal y As Integer) As Integer result = x + y Return result End Function End Class Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim refCls As New testClass() Dim type As Type = refCls.[GetType]() For Each refInfo As MemberInfo In type.GetMembers() MessageBox.Show(refInfo.Name) Next End Sub End Class (C) 2016    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.