Question

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.

Was it helpful?

Solution

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();

OTHER TIPS

The is operator in C# is used to check the object type and it returns a bool value: true if the object is the same type and false if not.

For null objects, it returns false.

The as operator does the same job of is operator but the difference is instead of bool, it returns the object if they are compatible to that type, else it returns null.

In the case of is operator, to type cast, we need to do two steps:

  1. Check the Type using is
  2. If it’s true then Type cast

Actually this affects the performance since each and every time the CLR will walk the inheritance hierarchy, checking each base type against the specified type. To avoid this, use as it will do it in one step. Only for checking the type should we use the is operator.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top