0

I'm new to C#, just a question on the use of "is" keyword. I saw one of my textbook was using:

if (obj is Person && obj != null)
{
   ...
}

but is obj != null redundant?

  • 4
    Yeap, redundant.`is` returns false for `null`. – MakePeaceGreatAgain May 23 '19 at 08:05
  • Correct, you can find more info in the [documentation](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/is) – Matthiee May 23 '19 at 08:05
  • 1
    Yes, it is. `null` is not a `Person`, **even** if the `obj` variable is of type `Person`. – Lasse V. Karlsen May 23 '19 at 08:06
  • Or, you can try it by yourself and see what's happening. – SᴇM May 23 '19 at 08:09
  • Possible duplicate of [Why does the is operator return false when given null?](https://stackoverflow.com/questions/7640043/why-does-the-is-operator-return-false-when-given-null) – SᴇM May 23 '19 at 08:12
  • It is redundant but it doesn't actually matter. The jitter optimizer catches this and entirely removes the obj != null check. Dead code elimination [is one](https://stackoverflow.com/a/4045073/17034) of its optimization strategies. – Hans Passant May 23 '19 at 10:03

2 Answers2

0

The is keyword evaluates type compatibility at runtime. It determines whether an object instance or the result of an expression can be converted to a specified type.

if (obj is Person) {
   // Do something if obj is a Person.
}

You can also check for null.

So don't perform a null check.

var obj = new object();              
Console.WriteLine(obj is null);

In this case else part will execute.

             object obj = null;

            if(obj is CustomData)
            {
                Console.WriteLine("Match");
            }
            else
            {
                Console.Write("Null");
            }

Although useful, I would really advise not using it and instead, use as. The as keyword is a defensive cast, which means that a cast will be attempted and if the object is not able to be cast to the supplied type null is returned instead.

The reason I’d advise against using it because it will actually cause you to perform 2 casts – one to check if the object is of the type and then a second to actually capture the casted value.

Refer This

Refer This

Hitesh Anshani
  • 1,499
  • 9
  • 19
0

I think very simply explain to you here

 Person obj = new Person();
 if (obj is Person && obj!=null){};

Is check the type and it will return a bool that is true or false. Is an operator never throw an error. Is refer metadata find out the type an object is found then it will return true otherwise return false.

Person obj = null;
if (obj is Person){//return always false}

if you try above code is return always return false.

obj!=null

!= is inequality operator if its operands are not equal it will return true otherwise false.

refer documentation "Is"

Equality Operator

SUNIL DHAPPADHULE
  • 2,755
  • 17
  • 32