Visual Basic .NET - Reflection in VB.NET

Reflection is a feature in VB.NET that allows a program to inspect and interact with its own structure at runtime. This means your program can examine information about classes, methods, properties, fields, and even create objects dynamically while it is running.

In simple words, Reflection lets a program look at itself.


Why Reflection is Important

Normally, when you write code, everything is known at compile time. For example, you know which class you are creating and which method you are calling. But sometimes, you may not know this information until the program is running. Reflection helps in such situations.

It is commonly used in:

  • Plugin systems

  • Framework development

  • Dependency injection

  • Testing tools

  • Object serialization


How Reflection Works

Reflection works through the System.Reflection namespace in VB.NET. It provides classes that allow you to:

  • Get information about a type (class, structure, interface)

  • Get details of methods and properties

  • Invoke methods dynamically

  • Create objects at runtime


Basic Example

Here is a simple example that gets information about a class:

Imports System.Reflection

Module Module1
    Sub Main()
        Dim t As Type = GetType(String)
        Console.WriteLine("Class Name: " & t.Name)

        For Each method In t.GetMethods()
            Console.WriteLine(method.Name)
        Next
    End Sub
End Module

Explanation:

  • GetType(String) gets metadata of the String class.

  • GetMethods() returns all methods available in that class.

  • The program prints all method names at runtime.


Creating an Object Using Reflection

You can also create an object dynamically:

Dim t As Type = Type.GetType("System.Text.StringBuilder")
Dim obj As Object = Activator.CreateInstance(t)

Here:

  • The class name is provided as a string.

  • CreateInstance creates the object at runtime.


Advantages of Reflection

  1. Allows dynamic programming.

  2. Useful in large frameworks.

  3. Helps in building flexible and reusable code.


Disadvantages of Reflection

  1. Slower than normal method calls.

  2. Makes code more complex.

  3. Can reduce performance if overused.


Conclusion

Reflection in VB.NET allows a program to examine and manipulate its own structure at runtime. It is powerful and useful for advanced programming scenarios such as dynamic object creation, method invocation, and framework development. However, it should be used carefully because it can impact performance and make code harder to understand.