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

C#asp.net.Net 2.0

C# Problem Overview


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

C# Solutions


Solution 1 - C#

This is one way:

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

Solution 2 - C#

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

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

instead of

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

Solution 3 - C#

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

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

Solution 4 - C#

Two well-known ways of doing it are :

  1. Using IS operator:

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

  2. Using AS operator (useful if you also need to work with the textBox instance) :

    var textBox = sender as TextBox;
    if (sender == null) {...}

Solution 5 - C#

If you use inheritance like:

public class BaseClass
{}
public class Foo : BaseClass
{}
public class Bar : BaseClass
{}

... Null resistant

if (obj?.GetType().BaseType != typeof(Bar)) { // ... }

or

if (!(sender is Foo)) { //... }

Solution 6 - C#

Try this.

var cont= textboxobject as Control;
if(cont.GetType().Name=="TextBox")
{
   MessageBox.show("textboxobject is a textbox");
} 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionroman mView Question on Stackoverflow
Solution 1 - C#Jon TackaburyView Answer on Stackoverflow
Solution 2 - C#Oleh HrechukhView Answer on Stackoverflow
Solution 3 - C#Wayne MolinaView Answer on Stackoverflow
Solution 4 - C#John-PhilipView Answer on Stackoverflow
Solution 5 - C#szydzikView Answer on Stackoverflow
Solution 6 - C#JoeeView Answer on Stackoverflow