What is the best way to cast from one type to another in C#? This question came up at work last week while I was looking through some older code. The code in question was using the C style casting syntax. I have started to use the "as" style cast more often and rewrote it. Then I decided to do some research into the differences between the two styles to find out if one really is better than the other.
The most obvious difference is that a C style case will throw and exception if the cast fails and the "as" style cast will simply return null. So first you need to take into consideration what these differences will have on your code. Will you need to wrap every cast in try/catch blocks? Not if you use the "as" style, but you will need to check for null. What about performance?
I read a dozen or so blog posts on the subject and they seemed to be pretty evenly divided with half insisting that one style was obviously superior and the other half convinced their chosen style was better. That didn't really help so I decided to do some testing on my own.
I've attached a small test project for reference, it will allow you to select the number of casts to perform and the style and return the total time and average for each cast. First let's see what the difference looks like in IL (o is of type object in these examples).
So there is a difference at the IL level but is one a better performer? I wrote three different test projects, the last of which you will find attached to this post. Why did I write three? Because with each test I was convinced that my results must be skewed because I was not seeing the performance difference I expected. I ran test casting 100,000, 1,000,000, 10,000,000 and 100,000,000 objects many times in difference orders, restarting the application between tests, not restarting between tests, clicking the button with my left hand, clicking with my right hand, every combination I could think of.
What did I discover? It was pretty anticlimactic. In my opinion the difference was completely negligible. That is, negligible if you aren't throwing exceptions when casting with the C style cast. The most stable set of test results I could get were casting 1,000,000 objects. In this case, either style averaged 10.1 seconds total and averaged 0.0101 milliseconds. We're talking about a difference of 0.00005 milliseconds per cast. I can't really get worked up over that. Of course, if you throw exceptions for each C style cast in that test, it's over 10 times slower. That's something to consider!
So will I pick one over the other? The answer is an emphatic "meh". In code I will probably use the "as" style. When doing things in markup related to databinding it's extremely useful to be able to use the C style cast and I will continue to do so.