-1

I'm fully aware why ascannot 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.

tsemer
  • 2,959
  • 3
  • 29
  • 26
  • 1
    `this code does the type check twice which has a performance cost,` Ok why not omitting the first check at all, and let it throw `InvalidCastException` when the type is incorrect? –  Jan 13 '16 at 11:20
  • @Kilanny author dont want to use try catch exception-based programming. – Jerry Switalski Jan 13 '16 at 11:24
  • @Kilanny that's a possibility but for consistency reasons you many times want to throw the expected/documented exception. For example, my code is implementing `IComparable`, which requires implementing CompareTo(object obj), and the `IComparable` documentation specifically states that implementers should throw `ArgumentException` (which makes sense). Pretty much the same reason why you null check method arguments and throw `ArgumentNullException` instead of just letting your code throw `NullReferenceException`. – tsemer Jan 13 '16 at 11:24
  • 1
    It is trade-off between performance and consistency. Author should decide. I don't even believe it would be costly to check twice –  Jan 13 '16 at 11:27
  • Would the downvoter care to comment? Otherwise I cannot know the issue you found with this question. – tsemer Jan 13 '16 at 13:49

1 Answers1

5

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194