Reflection in .Net

Outline

All .net assemblies have ‘METADATA' information stored about the type defined in MODULES. This metadata information can be accessed by a mechanism called as ‘REFLECTION'.

Introduction

Reflection is used when you don't know at compile time which time your object is or what action to do or on what property. REFLECTION provides several functionalities to assembly ‘METADATA'. Through using reflection you can also dynamically invoke methods. For invoking methods you need to add a namespace, as given below-

System.Type.Invokemember //invoking method //

You can dynamically invoke methods, on basis of that example:

Ex

Public Class Ref

    Private Sub Ref_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        Dim Pobjtype As Type

        Dim PobjObject As Object

        Dim objButtons As New Windows.Forms.Button()

        Pobjtype = PobjButtons.Get Type ()

        For Each PobjObject In Pobjtype.GetMembers

            LstDisplay.Items.add(PobjObject.ToString())

        Next

    End Sub

End Class


Image-1.jpg


Sample source code mentioned above uses reflection to browse through ‘BUTTON' class. If you compile and run that program, you will get output as shown in the image display.

Applications

There are many uses for reflection. The .Net Framework uses it for

  • Serialization
  • Data Binding
  • For Creating Tools

(It can also be used for creating tools) that examine your code like Reflector, FxCop and NUnit as well as ORM database frameworks. It has a wide variety of uses at runtime from logging specific things about an object to Dependency Injection Frameworks. It can also be used to dynamically execute methods or set properties at runtime as is done with custom attributes. It can also be used in higher level programming such as meta programming and self-modifying code.

Conclusion

It can also be very useful when testing your application, e.g. unit tests or other types of test frameworks.

Ex

Create an xml file (or some other input data file in suitable format) and have your program analyze it and call methods that are defined in the file. This is how ‘Fitnesse work'.

Ebook Download
View all
Learn
View all