I’ve recently encountered code which looks something like:
var someInstance = someParameter as ISomething;
someInstance.DoSomething();
The problem with this code is that it is wide open for a highly unhelpful NullReferenceException. If someParameter cannot be cast to ISomething the as operator will return null. But this code doesn’t check if someInstance is null. It makes the assumption that someParameter may be case to ISomething, even though in practice this assumption may not hold.
There are two solutions to this. You may replace the use of the as operator with an explicit cast. This will throw an InvalidCastException if the cast cannot be performed, which at least is more informative that the NullReferenceException. It’s also going to be somewhat faster but the performance gain will be sufficiently trivial that this is unlikely to be a useful optimisation. It also makes the code more explicit in what it expects which aids readability.
The preferred solution would be to check the result of the as operator for null and handle this case appropriately. In many cases this would be to throw an exception, but this exception may be more informative than a generic InvalidCastException or NullReferenceException. In general you should throw a specific exception that provides meaningful information in the context, rather than a technical exception(what went wrong rather than how). In other cases there may be an appropriate alternate activity to be performed, or the method could simply do nothing in this case. Regardless of the appropriate behaviour it is important that it be considered and the code actually implement this behaviour.