Dynamically Calling Methods
 
Published: 29 Apr 2004
Unedited - Community Contributed
Abstract
This article briefly introduces Reflection to users and how to use it when writing your code. The System.Reflection namespace contains all of the tools needed to provide a view (in code) of any assembly in .NET.
by . .
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 29870/ 61

Introduction

There are a lot of little known features in .NET that can sometimes prove useful in the line of duty, calling methods is one of them. Have you ever needed to get more information about a method through code? For example, is it public, what does it belong to, what are it's parameters? You can do all of this through code and it's quite easy. This article will show you about information stored in a Type as well as the MethodInfo class and how they can be used to look at and even execute a method without actually calling it yourself.

Reflection

Types

Later on I will go into this in greater detail, but this will be just a quick overview here.

You probably know that when you create a class, you are essentially creating a type. A lot of people underestimate the power of a type, you may have used GetType once in a while, but you may not know the underlying power of it. The Type class contains a heck of a lot of information about an type that you can access and then can lead on to some pretty interesting abilities.

System.Reflection

The System.Reflection namespace contains all of the tools needed to provide a view (in code) of any assembly in .NET. If you take a look at the Object Browser in VS.NET, that is the equivalent of using System.Reflection to find out about all of that information. Intellisense in VS.NET is also like using System.Reflection and Lutz Roeder's .NET Reflector uses System.Reflection to browse an assembly.

But why would you use System.Reflection?

Let's say that you were given an assembly and you have no idea what it contains or does, you could use reflection to find out what's in it and how it works.
Or, if you were developing a dynamic documentation system, then you could just place an assembly in the /bin directory and develop an application that used reflection to dynamically generate information and documentation about the assembly (much like the Comment Web Pages with XML Code Comments in VS.NET).

MethodInfo

MethodInfo is a class within System.Reflection that allows you to get information about specific methods (which I will be using in this article). For example, you can give it a method and you can get all sorts of properties and methods back which you can use to examine that method.

Getting Information About Types

In the following examples, I will be using a simple ASP.NET page with code-behind (because in code-behind the class is clearly defined for you).

GetType returns a Type class with information about a particular type. Examine the following code -

Public Class WebForm3
Inherits
System.Web.UI.Page

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim
mtype As System.Type = GetType(WebForm3)
...

mtype now contains information about WebForm3. And if it were to do something like -

Response.Write(mtype.Assembly)
Response.Write("<br>")
Response.Write(mtype.FullName)
Response.Write("<br>")
Response.Write("<table border=""1"">")
Dim
member As System.Reflection.MemberInfo
For
Each member In mtype.GetMembers
Response.Write("<tr><td>")
Response.Write(member.Name)
Response.Write("</td><td>")
Response.Write(member.MemberType.ToString())
Response.Write("</td></tr>")
Next
Response.Write("</table>")

Live Demo

You will get a table of every single member in the Type. See the live demo.

I probably jumped ahead a bit with the GetMembers call, but all you need to know about it is that it returns an array of MemberInfo objects that contain information about every member in the type. If you take a look at the demo, you will see a lot of methods and properties that you didn't know existed. This is because it not only takes WebForm3, but also -

  • System.Web.UI.Page
  • System.Web.UI.TemplateControl
  • System.Web.UI.Control
  • System.Object

Because that is how far back the inheritance goes on WebForm3.

MethodInfo

MethodInfo is a class that stores method information and the GetMethod function of System.Type returns a fully loaded MethodInfo class for you to use.

Public Class WebForm3
Inherits
System.Web.UI.Page

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim
mtype As Type = GetType(WebForm3)
Dim
minfo As System.Reflection.MethodInfo = mtype.GetMethod("Return1")
End
Sub

Public Function Return1(ByVal name As String) As String
Return
"Hello " & name
End
Function

End Class

This piece of code fills minfo with lots of information about the function Return1.

Parameter Information

       Take a look at the following code -

Response.Write("<table border=""1"">")
Dim
parameter As System.Reflection.ParameterInfo
For
Each parameter In minfo.GetParameters()
Response.Write("<tr><td>")
Response.Write(parameter.Name)
Response.Write("</td><td>")
Response.Write(parameter.ParameterType.ToString())
Response.Write("</td></tr>")
Next
Response.Write("</table>")

Live Demo

This does very much the same as the MemberInfo one before, but this time with parameters of a function. You will notice that it only returns one parameter (name) for Return1.

Invoking

Now here is the really interesting part - You can also call a method using MethodInfo.

Let's say that you had the name of a method stored in a variable. You can't go - variablename(). So you have to use MethodInfo.

MethodInfo.Invoke takes two parameters - The instance that created the method and the parameters (in an object array).

Take a look at the following code -

Public Class WebForm3
Inherits
System.Web.UI.Page

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim
mtype As Type = GetType(WebForm3)
Dim
minfo As System.Reflection.MethodInfo = mtype.GetMethod("Return1")

Dim
myparamarray() As Object = {"Sample Name"}    'New
Response.Write(minfo.Invoke(Me, myparamarray))    'New
End
Sub

Public Function Return1(ByVal name As String) As String
Return
"Hello " & name
End
Function

End Class

The two new lines create a parameter array with a field for each parameter and it's value  and then uses minfo.Invoke to call the function and write it's results to the screen. The same would work with a method.

Summary

This article has kind of been your quick introduction to reflection in .NET, but at the same time focused on the aspect of methods and specifically the MethodInfo class. There is a lot more out there on reflection, so check out the documentation on the System.Reflection namespace and see what comes up.

Also, as a quick point of interest, you can actually shorten the entire Page_Load method above to -

Dim myparamarray() As Object = {"Sample Name"}
Response.Write(GetType(WebForm3).GetMethod("Return1").Invoke(Me, myparamarray))


User Comments

No comments posted yet.

Product Spotlight
Product Spotlight 





Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2021 ASPAlliance.com  |  Page Processed at 2021-02-26 11:05:30 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search