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.
You can use:
var maybeValueType = obj as MyValueType?;
if (maybeValueType != null)
{
// Use maybeValueType.Value
}
However, this performs worse than is
+ casting - or at least has in the past.
It's possible that C# 7 will fix this with:
if (obj is MyValueType value)
{
// Use value here
}
... but obviously until C# 7 is more pinned down, it's not certain.
See more on this question at Stackoverflow