Check if object is NOT of type (!= equivalent for “IS”) – C#

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{} 🙂

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

This is one way:

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

Method 2

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

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

instead of

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

Method 3

Couldn’t you also do the more verbose “old” way, before the is keyword:

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

Method 4

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

Method 5

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)) { //... }

Method 6

Try this.

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x