2

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;
}

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

2

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.....

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.