C# – Switch Operators. != null (Is not null).

Updated on October 9, 2018 in [A] Other Answers
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
4 on October 9, 2018

Hi Everyone,

I have an case in a switch that i need to run if it’s not true. I’ve tried a few things without success.

So I decided to make my first post here on Brackeys.

I’ve googled it but, I am new to programming and not sure what to google on.

I’ve tried with () and without on those below and more.

!= null // Error = “Invalid expression ‘!='”

add != null // Error = “Cannot implicitly convert type ‘bool’ to ‘string'”

!null = Error = “Operator ‘!’ cannot be applied to operand ‘<Null>'”

a few rows of my code:

private void Calculate(Nullable<int> addNum, string add)
{
switch(add)
{
           case (!= null): // <---------------- This is the problem.
                    // do something.
                    return;
            case ("/"):
                     //do something..
                     return;
}
}
  • Liked by
Reply
3 on October 9, 2018

!= null

is not a string. Try “!= null” with the quotes.

 

on October 9, 2018

Thanks for quick reply, 😀

But i want it as a bool. is that possible with an switch?
So it runs like below. if “add is not null” it will start.

if(add != null)
Wise
on October 9, 2018

No, not with switch. You’ll need to use an if statement for that.

Switch only does comparisons.

 

on October 9, 2018

Ow, Then I’ve learned something new today again.  🙂

Thanks a lot for your fast replies.

Show more replies
  • Liked by
Reply
Cancel