Wednesday, February 07, 2007

.NET Reflection

Simple stuff for many guys.. :) When I do not get the expected resuts only I realized I have done something wrong.. So, it's worth to have a post on this...

The requirement is to invoke a method through reflections which accepts a parameter by ref.

This is the correct way of doing it. Yes, it's simple as that :)

[VB.Net]
Dim assm As [Assembly]
Dim global As Type
Dim method As MethodInfo
Dim params() As Object
Dim keyId as String

assm = [Assembly].Load("AssemblyName")
global = assm.GetType("AssemblyName.ModuleName")

params = New Object() {keyId}

method = global.GetMethod("ValidateKey")

'//Since we are calling a module we use Nothing as the first paramater
'//else First Parameter = Activator.CreateInstance(global);
method.Invoke(Nothing, params)

'//Get back the updated value
keyId = params(0)

This is the wrong way of doing it. You can be tempted to do this way, but you will never get the updated value back.

assm = [Assembly].Load("AssemblyName")
global = assm.GetType("AssemblyName.ModuleName")

method = global.GetMethod("ValidateKey")

'//Since we are calling a module we use Nothing as the first paramater
'//else First Parameter = Activator.CreateInstance(global);
method.Invoke(Nothing, New Object() {keyId})

'//You will never get back the updated value in 'keyId'

1 comment:

  1. Lets say I have a class A and class B and let say A has a reference to B,
    The methods are as follows
    public B GetB() -> found in A
    Public int GetValue() -> found in B

    How do I invoke GetValue() provided that i have an instance of A using reflection.

    Althoug I can first invoke GetB() on the A instace and get an instance of B and then invoke GetValue() on that instance of B, I am looking for a one line method invocation, Are there and Binding Flags for these sort of invocations?

    ReplyDelete