简体   繁体   中英

Are there edge cases for checking if a string is null?

I recently took ownership of some code from an author that is no longer with the company. Throughout the code I'm finding this line

if (string.Compare(string.Empty, textbox1.Text, true) == 0)

I'm not the most advanced C# programmer, but to me that seems functionally the same as

if (textbox1.Text == "")

Is there any edge case that the first line will catch that the second one won't?

Actually, you should use String.IsNullOrEmpty(textbox1.Text) instead.

As pointed out in the comments, String.IsNullOrWhitespace is especially useful since you're working with GUI controls, which often may contain just whitespace, and not actually be an "empty" string.

It is comparing string ignoring case , but its a bad way of doing it. String.Equals has an overload for comparing strings with ignoring case.

To check if string consist of empty string, String.IsNullOrEmpty should be used, if you are using .Net framework 4.0 or higher and you want to consider space as empty string then you can use string.IsNullOrWhiteSpace .

If you only want to compare the value with empty string then textbox1.Text == "" or textbox1.Text == string.Empty is enough.

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