0

I am starting out with C# and I think I understand && and || when they are used as bool, but I was wondering how to use them in a text string like this:

if (label1.Text == "Its Hot outside" || "Its warm outside")
{
    //picture of a sun
    picturebox.Show();
}

When I try something like this it gives me

Operator '||' cannot be applied to operands of type 'bool' and 'string'

The && works fine here, but how would I apply an "or" condition?

janw
  • 8,758
  • 11
  • 40
  • 62
  • 4
    It should be like this if (label1.Text == "Its Hot outside" || label1.Text == "Its warm outside"). Please go through [c# operators](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/) – neelesh bodgal Jul 17 '20 at 13:36
  • An addition: if you really need to check many strings against another string, you can put all strings into an array and check: `myArray.Cotains(label1.Text)` where `myArray = ["Its Hot outside", "Its warm outside"]` – nilsK Jul 17 '20 at 14:01
  • 2
    "The && works fine here" No, pretty sure you'd get the same error message. How could it be both anyways?... – Idle_Mind Jul 17 '20 at 14:09

1 Answers1

1

Since you are learning, I will take a little time to try and explain in a very basic way. If you don't understand, ask questions till you do. Best way to learn!!!

Now, its not a good idea to write code that way. the idea is to check if label1.Text is equal to "Its Hot outside" OR label1.Text is equal to "Its warm outside".

In regular English expression you can say it as it is but in programming, computers are not that smart(FACT), they need everything to be told them in clear language. this is called logics.

With this, a better logic to do this is;

if (label1.Text == "Its Hot outside" || label1.Text == "Its warm outside")
    {
      //picture of a sun
      picturebox.Show();
    }

What you have initially done is saying

If label1.Text is equal to the string "Its Hot outside" OR if "Its warm outside". the last part is not evaluated as a boolean, it's a string, which is the cause for the exception message: "Operator || cannot be applied to operands of type bool and string". Both operands must be boolean types.

What I have done is saying;

If label1.Text is equal to the string "Its Hot outside"

OR

If label1.Text is equal to the string "Its warm outside"

So it checks label1.Text against each string provided.

And this is really how to build logics for a computer.

This link could do you some good: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/

mw509
  • 1,957
  • 1
  • 19
  • 25