简体   繁体   中英

TextBox.Clear() or TextBox.Text = string.Empty

Is there any difference between them? Thank you

TextBox.Clear();  
TextBox.Text = string.Empty;

In practice: nope. Internally, there is. Both clear the text in completely different ways.

I wouldn't dare to tell you which one is better, but if you want to follow the sources, here's for Clear() and here's what it does when you change Text

--- Clear()

The Clear() method does more than just remove the text from the TextBox. It deletes all content and resets the text selection.

-- String.Empty

For some obscure reason string.Empty is not a constant. That means that in a number of cases where a compile-time constant is required, string.Empty isn't even legal. This includes case * blocks in switch statements, default values of optional parameters, parameters and properties in applying attributes, and a lot of other situations (left to the reader)*. So given that string.Empty is disallowed in some common situations.

One important difference is that using TextBox.Clear(); will clear the TextBox content, but it will keep any bindings intact.

If you use TextBox.Text = string.Empty; , any existing binding will be overridden.

For example, if you use Text binding like this:

<TextBox Text="{Binding Path=Description}"></TextBox>

Then you must use the Clear() method. Otherwise, it will break your binding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM