vb.netreflectionfriendfieldinfo

How to get the fieldInfo for a Friend WithEvents member?


I have the following member defined in a vb.net Form, MyForm:

Friend WithEvents myTab As Tab

I am trying to get this member using the following code:

Dim FieldInfo As System.Reflection.FieldInfo = MyForm.GetType.GetField("myTab", Reflection.BindingFlags.Instance Or Reflection.BindingFlags.NonPublic)

, but I am always getting Nothing in return. If I try:

Dim MemberInfo As System.Reflection.MemberInfo = MyForm.GetType.GetMember("myTab", Reflection.BindingFlags.Instance Or Reflection.BindingFlags.NonPublic)(0)

, I do get the member but I cannot get its value.

Are there other BindingFlags that need to be used to get the FieldInfo of a member with the Friend WithEvents modifier?


Solution

  • Yes, this can't work as written. The VB compiler gives a WithEvents member special treatment to implement its feature. After it is done, your myTab variable is not a field anymore. Something you can see when you look at the generated assembly with the ildasm.exe utility. You'll see:

    Not sure which way you actually want to go, you need the property if you want to tinker with events. So it is either one of these you need:

    Dim info = MyForm.GetType().GetField("_myTab", _
                   BindingFlags.Instance Or BindingFlags.NonPublic)
    

    Or

    Dim info = myForm.GetType().GetProperty("myTab", _
                   BindingFlags.Instance Or BindingFlags.NonPublic)
    

    Probably the first one.