What is the difference between these three ways to clear a Textbox?

c#, textbox, wpf

Solution

The `Clear()` method does more than just remove the text from the `TextBox`. It deletes all content and resets the text selection and caret as @syned's answer nicely shows.

For the `txtUserName.Text = "";` example, the Framework will create an empty `string` object if one does not already exist in the string pool and set it to the `Text` property. However, if the string `""` has been used already in the application, then the Framework will use this value from the pool.

For the `txtUserName.Text = string.Empty;` example, the Framework will not create an empty `string` object, instead referring to an empty string constant, and set this to the `Text` property.

In performance tests, it has been shown (in the In C#, should I use string.Empty or String.Empty or “”? post) that there really is no useful difference between the latter two examples. Calling the `Clear()` method is definitely the slowest, but that is clearly because it has other work to do as well as clearing the text. Even so, the difference in performance between the three options is still virtually unnoticeable.

Problem

I am bit confused between the below three ways to clear the contents of a textbox. I am working with WPF and found All are working, but I am unable to find the difference. Can someone please explain to me about it with some examples? - `txtUserName.Clear();` - `txtUserName.Text = string.Empty;` - `txtUserName.Text = "";`

Original source

Related problems