In development blogs, online code examples and (recently) even a book, I keep stumbling about code like this:
var y = x as T;
y.SomeMethod();
or, even worse:
(x as T).SomeMethod();
That doesn’t make sense to me. If you are sure that x
is of type T
, you should use a direct cast: (T)x
. If you are not sure, you can use as
but need to check for null
before performing some operation. All that the above code does is to turn a (useful) InvalidCastException
into a (useless) NullReferenceException
.
Am I the only one who thinks that this a blatant abuse of the as
keyword? Or did I miss something obvious and the above pattern actually makes sense?