user9248102
user9248102

Reputation: 299

Expression is always true, even though it isn't

I have the following code:

if (!(sender is Button b)) return false;
if (!(sender is ToolStripMenuItem menuItem)) return false; // always true

switch (b.Name)
{
    //some code
}

So, the second line is always assumed to be true for some reason I can't determine. If I move it first and the first one second, then the button line is always assumed true. No matter which line I put second, it's always assumed always true, but not if it's first.

I am trying to understand why is that happening and how to fix it. Any help is appreciated.

Upvotes: 1

Views: 80

Answers (2)

Scott Perham
Scott Perham

Reputation: 2470

Based on your comment and requirement to execute code depending on which type sender is, how about this...

switch (sender)
{
    case Button b:
        //Do button stuff;
        break;
    case ToolStripMenuItem menuItem:
        //Do menu item stuff;
        break;
    default:
        return false;
}

Upvotes: 3

SLaks
SLaks

Reputation: 887877

The first line guarantees that sender is Button.

That means it cannot also be ToolStripMenuItem, so the second check will always succeed.

Upvotes: 2

Related Questions