views:

4661

answers:

3

This works just fine:

    protected void txtTest_Load(object sender, EventArgs e)
    {
        if (sender is TextBox) {...}

    }

is there a way to check if sender is NOT a TextBox, some kind of an equivalent of != for "is"?

Please, don't suggest moving the logic to ELSE{} :)

thank you.

I knew it had to be easy :)

+23  A: 

This is one way:

if (!(sender is TextBox)) {...}
Jon Tackabury
this answer is not worth 82 reputation.
orlandu63
@orlandu63: then you should not have up-voted it.
Shog9
For this particular situation I prefer if (sender is TextBox == false). Less clunky syntax like this.
hmemcpy
@hmemcpy: Personally, i cringe whenever i see a comparison to a boolean constant. Probably my C background showing through... Still, makes my skin crawl, and there's no way i'd leave it alone in code i was editing.
Shog9
Hey, you forgot "first!" in your post ;)
Leonidas
A: 

Jon T posted the correct answer. You should see the (sender is Textbox) as a bool, which probably makes it easier to understand.

netterdotter
A: 

DISCLAIMER: My C# skills are a little rusty.

Couldn't you also do the more verbose "old" way, before the is keyword:

if (sender.GetType() != typeof(TextBox)) { // ... }
Wayne M
Sure, you could, but do note that the "is" keyword matches any object derived from TextBox, whereas this typeof() check only matches TextBoxes.
mquander
Ah, I did not know that. Learn something new every day :)
Wayne M