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?
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?
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.
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.