Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a TextChanged event fire if the text hasn't changed?

I'm working on customizing (and fixing) a large application for a client which was purchased from another source. The code we ended up getting was most certainly NOT the actual code used in production by the source client. That being said, I ran into this today:

if (lblCurrentValueOfContractAmount.Text == "0.0")
   lblCurrentValueOfContractAmount.Text = "0.0";

And no, I'm not joking. My first inclination was to just remove it, then I started talking to another developer who mentioned that there might be some clandestine stuff going on here, like somebody subscribed to the label's text being changed, etc. Honestly I'm not that concerned about it, so I'm just going to leave it in. However, this brings me to my question:

Let's assume that there is someone subscribed to TextChanged, for example. If the text doesn't actually change, would the compiler optimize that whole statement away? Would the event actually fire?

like image 328
DrewJordan Avatar asked Apr 17 '15 18:04

DrewJordan


People also ask

Which event is generated when TextBox text is changed?

The event handler is called whenever the contents of the TextBox control are changed, either by a user or programmatically. This event fires when the TextBox control is created and initially populated with text.

Which event is fired when there is a change in the content of the text box?

The TextChanged event is raised when the content of the text box changes between posts to the server. The event is only raised if the text is changed by the user; the event is not raised if the text is changed programmatically.

What is text change event in Visual Basic?

The TextChanged event occurs whenever the text is changed, by the user or programmatically. In your case your A_TextChanged eventhandler is changing B's text, so that B_TextChanged is called … Adding some Debug.


1 Answers

Assuming you have a Winforms Label (or other Control derived class), the code will not fire a change event and therefore that code has no side effects and can be removed. http://referencesource.microsoft.com/#System.Windows.Forms/winforms/Managed/System/WinForms/Control.cs,9884211b7ff61817

        public virtual string Text {
        get { ... }

        set {
            if (value == null) {
                value = "";
            }

            if (value == Text) {
                return;
            }
            // omitted remainder
        }
    }
like image 78
Steve Mitcham Avatar answered Oct 19 '22 16:10

Steve Mitcham