Search:
Locator+ Code:
FTPOnline Channels Conferences Resources Hot Topics Partner Sites Magazines About FTP RSS 2.0 Feed
 

Reflect Over .NET Framework Assemblies
Use the System.Reflection namespace to invoke types and members dynamically at run time.
by Keith Pleas

VSLive! Orlando, September 17, 2002

Note: Keith Pleas is presenting "Leverage .NET Framework Using Visual Basic .NET" at VBITS Orlando, Tuesday, September 17. This tip is from that session.

One of the major features of .NET Framework managed code is the ability to examine—or "reflect over"—assembly metadata. Using the System.Reflection namespace, you can discover types and members (like properties and events) and instantiate or invoke them dynamically, at run time, from within your own code.

Assuming "asy" is a reference to a valid assembly of type System.Reflection.Assembly, this code snippet iterates over all the types in that assembly and—if they are marked public—adds the type name to a listbox:

        For Each typ In asy.GetTypes()
            ctrTypes += 1
            If typ.IsPublic = True Then
                lstTypes.Items.Add(typ.Name)
                ctrPublic += 1
            End If
        Next

So, how do you get a pointer to an assembly? If for some reason you wanted to examine your own assembly, you could simply use:

        asy = Me.GetType().Assembly

However, it's probably more interesting to examine other assemblies. Here is just one way to load an assembly (in this case, by specifying the assembly filename in a textbox):

asy = System.Reflection.Assembly.LoadFrom(cboAssemblies.Text)

Of course, once you start loading assemblies—or, more importantly, reflecting over assemblies running in other processes—you'll need sufficient permissions to do this. The ability to reflect over an assembly is given only to those applications that execute with "full trust," so not just any random managed code is going to be able to do this. However, because full-trust code can examine an assembly, you might want to protect certain intellectual property using additional steps, such as cryptography. But that's another topic entirely…

About the Author
Keith Pleas is a Visual Studio Magazine contributing editor. He was responsible for organizing and presenting the Microsoft-sponsored Windows 2000 Pre-Season and Implementation Mini-Camps. He has also contributed to several Microsoft Professional Certification exams.