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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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.