问题描述:

The aim of this code is to repeat the question "Please enter your name" if the user does not input any data. However I am having trouble with making this work with the if statement.

while (true)

{

Console.WriteLine("Please enter your name:");

string line = Console.ReadLine();

if (line=String.empty) //I'm having difficulty making this a valid statement

Console.WriteLine("Your entry was blank");

else break;

}

网友答案:

As looking your code, the error is in using making condition....You are using assignment operator(=) instead of comparision operator(==)......So do like this :

if (line == String.Empty)
{
       //Put your code
}

Or,You can simply do like this:

if (string.IsNullOrEmpty(line)) 
           Console.WriteLine("Your entry was blank");

Or, you can use string.IsNullOrWhitespace as Oded answer specified but it is only available in .NET 4 or above.....

网友答案:

line=String.empty is an assignment, using the assignment (=) operator. It assigns string.Empty to line.

You should be using the comparison operator ==.

Better yet, look at the string.IsNullOrWhitespace method (.NET 4.0+), or string.IsNullOrEmpty.

网友答案:

Just change your if clause to if(line == "") and things should be just fine.

= is the assignment operator and you want to compare the values, therefore you should use the == comparison operator.

相关阅读:
Top