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 = "";
Some say String.Empty is faster than "" however String.EMpty is Static member that is initialized to ""
When we call
String.Empty
theIL
makes call toWhereas for "" it does not
SO logically it would make more sense that "" is more efficient than String.Empty
Let's go through the commands one by one.
The
Clear()
command assigns the texbox an empty string just like the next example. Source (best explination is given by syned on this point)Now the
string.Empty
the actuall code for it isMeaning that you assign the string "" after compile time.
Now here you just assign the "" string directly to the object on compile time.
Small side note
txtUserName.Text = "";
is faster thantxtUserName.Text = string.Empty;
Source""
creates an object whileString.Empty
creates no object. So it is more efficient to use String.Empty.Refference: String.Empty vs ""
Regarding
.Clear()
i didnot get better answer then @syned's answer.The string.Empty field is an empty string literal. It is slightly different from an empty string literal constant " ". There is a subtle difference—but one that could be significant in some scenarios. It changes the meaning of a program
We use string.Empty and "" in a C# program. The string.Empty field is initialized to "" at runtime by the .NET Framework.
You cannot use string.Empty as a switch case, because
it cannot be determined at compile-time by the C# compiler.
Which explain the differences of string.empty and ""
The
Clear()
method does more than just remove the text from theTextBox
. It deletes all content and resets the text selection