C# Explicit Casts

Most programmers know how to use an explicit cast. In C# the way of handling is as follows:

int i = 0;

decimal d = 3.4M;

i = (int)d;

This is a trivial case and my main point is how will the explicit casting operation handle null references.

When attempting to cast a null reference to another reference type, the casting will not throw an exception. So be careful after attempting to access a method or property from a reference after casting, it is a possibility the reference is set to null. I (try to) always check for a null reference before attempting to cast in hoping I will save some CPU cycles.

Related Posts