Check if object is NOT of type (!= equivalent for "IS") - C#

Viewed 69789

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{} :)

6 Answers

This is one way:

if (!(sender is TextBox)) {...}

C# 9 allows using the not operator. You can just use

if (sender is not TextBox) {...}

instead of

if (!(sender is TextBox)) {...}

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

if (sender.GetType() != typeof(TextBox)) { // ... }
Related