Attila Alan
Attila Alan

Reputation: 75

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

Is there any difference between them? Thank you

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

Upvotes: 2

Views: 8087

Answers (3)

Tomáš Oplatek
Tomáš Oplatek

Reputation: 360

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.

Upvotes: 1

Jcl
Jcl

Reputation: 28272

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

Upvotes: 6

Er Ketan Vavadiya
Er Ketan Vavadiya

Reputation: 281

--- 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.

Upvotes: -3

Related Questions