Repository navigation
Using boxing ((int)(object)value) instead of pattern matching (value is int intValue) in number classes #102480
|
In the int result;
if (typeof(TOther) == typeof(int))
{
result = (int)(object)value;
}
else if (!TryConvertFromChecked(value, out result) && !TOther.TryConvertToChecked(value, out result))
{
ThrowHelper.ThrowNotSupportedException();
}
return result;I'm interested in this condition in line 3: if (typeof(TOther) == typeof(int))
{
result = (int)(object)value;
}Wouldn't it be better to write it like this: if (value is int intValue)
{
result = intValue;
}As far as I understand it, this would avoid the boxing of However, since I'm seeing this pattern in a lot of places (especially in the TryConvertFromChecked methods), it would seem, I'm missing something here. Why didn't the author use pattern matching here? |
Answered by
huoyaoyuan
May 21, 2024
Replies: 1 comment 1 reply
1 reply
Answer selected by
skrysm
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The
(ConcreteType)(object)genericVariableis a special sequence in generic context. It's specially understood by the JIT. The generic mechanism doesn't allow casting a variable typed withTto be casted to arbitrary destination type. The fake box instruction is to workaround the limitation. Even non-boxable type is also allowed with the special sequence (https://github.com/dotnet/runtime/blob/main/docs/design/features/byreflike-generics.md#special-il-sequences). With generic instantiation, no actual boxing will be performed by this special sequence.Pattern matching actually generates more
boxinstructions. See the example at https://sharplab.io/#v2:EYLgxg9gTgpgtADwGwBYA0AXEBLANgHwAEAmARg…