I just discovered this operator and I was wondering if it is safe to use or not.
I mean, in Java our teachers always told us to avoid instanceof() because it breaks polymorphism and often shows poor coding.
I just discovered this operator and I was wondering if it is safe to use or not.
I mean, in Java our teachers always told us to avoid instanceof() because it breaks polymorphism and often shows poor coding.
It's 'safe'. At least it's safer to use this check, rather than just cast and assume the type! You may prefer to use the as operator, which performs the cast to the required type if appropriate, or returns null otherwise. Just remember to check for null.
But often an explicit type check is an indication that something is not quite right with your model. Sometimes it's unavoidable, but if you're doing this a lot, I would take a step back and reconsider your model.
if (obj is FooObject)
{
((FooObject)obj).Foo();
}
Is equivalent to
if (obj instanceof FooObject) {
((FooObject)obj).foo();
}
With pattern-matching (C# 7+) you can now do:
if(foo is Bar bar) {
return bar;
}
Here, bar
is equivalent to (Bar)foo
.
Switch statements are also relevant, oddly enough:
switch (x)
{
case int i:
Console.WriteLine ("It's an int!");
Console.WriteLine ($"The square of {i} is {i * i}");
break;
case string s:
Console.WriteLine ("It's a string");
Console.WriteLine ($"The length of {s} is {s.Length}");
break;
default:
Console.WriteLine ("I don't know what x is");
break;
}