What is the difference between these three ways to

2019-03-09 22:11发布

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 = "";

标签: c# wpf textbox
10条回答
手持菜刀,她持情操
2楼-- · 2019-03-09 22:57

Some say String.Empty is faster than "" however String.EMpty is Static member that is initialized to ""

When we call String.Empty the IL makes call to

mscorlib.dll 

IL_0007:  ldsfld     string [mscorlib]System.String::Empty

Whereas for "" it does not

IL_001a:  ldstr      ""

SO logically it would make more sense that "" is more efficient than String.Empty

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-03-09 23:01

Let's go through the commands one by one.

txtUserName.Clear();

The Clear() command assigns the texbox an empty string just like the next example. Source (best explination is given by syned on this point)

txtUserName.Text = string.Empty;

Now the string.Empty the actuall code for it is

static String()
{
    Empty = "";
}

Meaning that you assign the string "" after compile time.

txtUserName.Text = "";

Now here you just assign the "" string directly to the object on compile time.

Small side note txtUserName.Text = ""; is faster than txtUserName.Text = string.Empty; Source

查看更多
Bombasti
4楼-- · 2019-03-09 23:03

"" creates an object while String.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.

查看更多
再贱就再见
5楼-- · 2019-03-09 23:04

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 the TextBox. It deletes all content and resets the text selection

查看更多
登录 后发表回答