[c#] Comparing strings in C# with OR in an if statement

I'm a newbie to C#, but can't seem to find anything about this problem. Here's what I'm trying to do:

string testString = txtBox1.Text;
string testString2 = txtBox2.Text;

if ((testString == "") || (testString2 == ""))
{
    MessageBox.Show("You must enter a value into both boxes");
    return;
} 

Basically I need to check to see if either txtBox1 or txtBox2 is blank. However I'm getting an error when running this. What's the proper way to do this (or is my approach all wrong)?

This question is related to c# string

The answer is


Try:

    if (textBox1.Text == "" || textBox2.Text == "")
    {
        // do something..
    }

Instead of:

    if (textBox1.Text == string.Empty || textBox2.Text == string.Empty)
    {
        // do something..
    }

Because string.Empty is different than - "".


The code provided is correct, I don't see any reason why it wouldn't work. You could also try if (string1.Equals(string2)) as suggested.

To do if (something OR something else), use ||:

if (condition_1 || condition_2) { ... }

use if (testString.Equals(testString2)).


try

if (testString.Equals(testString2)){
}

Here's a more valid way which also check if your textbox is filled with only blanks.

// When spaces are not allowed
if (string.IsNullOrWhiteSpace(txtBox1.Text) || string.IsNullOrWhiteSpace(txtBox2.Text))
  //...give error...

// When spaces are allowed
if (string.IsNullOrEmpty(txtBox1.Text) || string.IsNullOrEmpty(txtBox2.Text))
  //...give error...

The edited answer of @Habib.OSU is also fine, this is just another approach.