Is there a good (technical) argument to use either one and not the other of the following ways to check if an instance is of a specific type? Is one of them error prone and should be avoided?
// Use "is".
bool isFolder = this.Parent is FolderEntity;
// Use "as".
bool isFolder = (this.Parent as FolderEntity) != null;
The intention of the code is to find out of the instance is a FolderEntity
. In that case, the code will branch. The code is not interested in the resulting object.
From a point of clear code, I would use "is". What I was wondering however if there is a reason to prefer the "as" way of doing it.
If you are only interested if something is of a certain type, and you don’t need that object as an object of that type, then just use is
. That way, you clearly convey your intention to check its type, and not to cast it into another type which would be a completely different intention.
That is regardless of its actual implementation, where both are somewhat implemented with each other.
But implementation detail is rarely important (and micro-optimization is more harmful), when you can choose to write something in clear way to match your intent.
As you said yourself, “the code is not interested in the resulting object”, so you don’t need to cast it into another type; you just need to check its type: So yes, let the code be clear about that and just use is
.
If, on the other hand, you would want to check its type but then also do something with it, you would do it like this:
FolderEntity folder = this.Parent as FolderEntity;
if (folder != null)
DoThingsWith(folder);
else
DoThingsWithoutTheParent();