I'm fully aware why as
cannot be used for value types. However, the only replacement I am aware of is:
if (!(obj is MyValueType)) { // Type check #1
// Exception or whatnot
}
var myValueType = (MyValueType)obj; // Type check #2
However, this code does the type check twice which has a performance cost, the same cost as
came to solve for reference types.
My question: Is there any better performant mechanism / syntax for value types?
The only single type checking mechanism I can think of is try/catch
, but that of course has a performance cost of its own, and I try to avoid exception-based programming when I can.