So reflection enables you to find out information about types in your assemblies during runtime. Using reflection, you can find out the details of an object's methods in terms of its access modifier ( private, public etc.), you can discover the name and types of parameters in a methods signature.
If you have used the class browser , then you can get an idea of the sort of information one can retrieve using reflection.
The System.Reflection namespace contains many classes and methods that provide you with the functionality just described above.
The need for Reflection
While there are many reasons to use reflection, let me give you a real life example. Say you are building a custom component in .NET that requires a XML file to be used along with your components DLL. You can store the XML file in the /bin directory with your DLL, but how will you access the XML file without knowing the correct path to the /bin directory? I'm sure this is a rhetorical question if you have understand even 10% of what I have wrote so far, but I'll tell you anyways: r e f l e c t i o n. I've created a sample code snippet for you that does just this. Keep reading…
Example usage of Reflection
Here's a neat little trick to find out the calling assemblies path.
// using System.IO;
// using System.Reflection;
public static string GetApplicationDirectory
{
get
{
return Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase).Replace(@"file:\", "");
}
}
You can also output the executing assembly information during runtime:
<%@ Page language="c#" %>
<%@ Import Namespace="System.Reflection"%>
<script language="C#" runat="server">
private void Page_Load(object sender, System.EventArgs e)
{
Assembly SampleAssembly;
// Display the name of the assembly currently executing
Response.Write("GetExecutingAssembly=" + Assembly.GetExecutingAssembly().FullName);
}
</script>
<html>
<head>
<title>CSharpFriend.com - ASP.NET Sample - reflection</title>
</head>
<body>
</body>
</html>
I hope you have understood some basic ideas of what reflection is and what information it can provide you with during runtime.
Enjoy!