‘Stupid’ Question 20: How should I do casting in C#? Should I use the prefix cast or the as-cast?
I remember when we learned about casting in school. It was when we learned about the hashtable. My teacher took the trash bin and walked around and put things it (even grabbing a few personal items from the students,- just for laughs). As some of the students on the front row got to fish out some of the items from the bin giggling he explained casting to us.
Casting in C# - how should I do this magic?
We learned to use the classic cast, we learned both ways, but the prefix cast stuck better with me in the beginning. I don’t know when, but at some point I started noticing ‘as’ casting in code examples and immediately liked the syntax better- it was more readable, even if I was skeptic to the lack of parentheses that I had learned to love. So I have to admit, I started using it without really looking into what it meant. I just assumed it was the same. But then I started getting weird exceptions. I was getting the dreaded NullReferenceException from my methods. What do you mean null??
So I asked myself, what is the difference between these two types of casting, and when should I use them?
The classic cast or prefix cast throws an InvalidCastException if the cast is not valid and should be used when you are expecting the cast to succeed - which seems to be the main recommendation (the question being why would you expect the casting to fail?- and is this (‘as’) the best way to handle that?)
With the ‘as’ casting a null will be returned if the conversion fails,- so this means that you can ‘test’ a cast – but also that the type has to be nullable or be able to take a null. This cast should be used when you are not sure if the casting will succeed.
Like somebody put it on stackoverflow:
Use as when it’s valid for an object not to be of the type that you want, and you want to act differently if it is.
I think I covered that in the article, but to sum up, here are two ways to think about it.
First, “as” means “I expect that sometimes this will not succeed, give me null in those cases”. A cast means “I expect that this will always succeed; if I am wrong, then please crash the program”.
Second, “as” means “I want to know what this object *really is*, not what it is convertible to by some representation-changing specially-defined conversion rule. A cast means “convert this thing using whatever crazy mechanism you need to do to make it work.”
Choose the one that matches the meaning you intend to implement. – Eric
Last modified on 2012-08-11