Need implicit type convert in "is" constant pattern matching #4401
Replies: 3 comments 11 replies
-
Try You need the same type when you are unboxing. |
Beta Was this translation helpful? Give feedback.
-
This feels like perhaps a use case for active patterns? |
Beta Was this translation helpful? Give feedback.
-
Rereading this thread, I was struct by something in this block: if (obj is int a && a > 0
|| obj is byte b && b > 0
|| obj is short c && c > 0
|| obj is long d && d > 0
|| obj is sbyte e && e > 0
|| obj is ushort f && f > 0
|| obj is uint g && g > 0
|| obj is ulong h && h > 0
|| obj is float i && i > 0
|| obj is double j && j > 0
|| obj is decimal k && k > 0
)
{
DoSomething();
} Across all these different types of numbers (different ranges, precisions, etc), comparisons with zero (0) are about the only meaningful common operation. Addition and subtraction can't be generalized because of the differences in range (code that could never overflow with int is extremely likely to with byte, for example). Same for multiplication. Division is a whole 'nother can of worms - some of the types support floating point division, others only integer based. Even if we restrict ourselves to just comparison operators, things don't work. Let's imagine for a moment that this desired code worked: if (obj is < 6) {
DoSomething();
} (The only differences are using If If it was forced (say, using I don't think relying on implicit conversions is a good idea. Instead, within the current bounds of C#, and assuming that var value = (double)Convert.ToDouble((dynamic)obj); Using dynamic forces overload resolution to happen at runtime (instead of compile time), so any of the numeric types supported by Issues to be aware of include performance (dynamic is slow, but not that slow, especially if you're working with human perceptible speeds), and exceptions (if |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
this code
obj is 0
, if i'm not sure theobj
's type isint
, then i dare not write like this, because the result is probably not as expected.This limits the use of
is
, so i hope it do type convert.Beta Was this translation helpful? Give feedback.
All reactions