Knowledge.ToString()

VB .Net – Calling a Function Calls Property Setter Method

I encountered a nasty bug (technically: design) when I was using an HTML Web control in a WinForms application. I am storing html and plain text version of text into a SQL table. This control has InnerHtml and InnerText properties. Both of these properties have getter and setter. I was calling a 3rd party dll function with webcontrol.InnerHtml and webcontrol.InnerText as an argument. Here is an example.

Dim plainText as String = 3rdParty.CheckForValue(webcontrol.InnerText)
Dim htmlText as String = 3rdParty.CheckForValue(webcontrol.InnerHtml)

As soon as I call 3rdParty.CheckForValue(webcontrol.InnerText), it was replacing the entire HTML content of webcontrol with a plain text. If I comment out the code, it worked as expected. It seems like somehow the InnerText property setter method is called as soon as I call “3rdParty.CheckForValue”. I tried to investigate the dll and found nothing wrong within the function code. But that was happening for sure.

Solution

Finally I figured out that “3rdParty.CheckForValue” had a ByRef parameter. In VB .Net if the function has ByRef parameter and passing argument is a property (and not a variable), internally values are copied into a temporary variable when the function is called and copied back into original variable (aka property setter is called) when the function returns. We can avoid this situation by copying the property value into a variable and then pass variable into a function.

Dim plainTextTemp as String = webcontrol.InnerText
Dim htmlTextTemp as String = webcontrol.InnerHtml

Dim plainText as String = 3rdParty.CheckForValue(plainTextTemp)
Dim htmlText as String = 3rdParty.CheckForValue(htmlTextTemp)

This is NOT a bug but is by VB .Net design.

Share

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *