I know that boxing then unboxing is computationally expensive, and it happens when casting a value type to object or other reference type then back to value type. However, does this happen when I'm casting long to ulong or vice versa.
I have following code:
ulong number = (ulong)IPAddress.NetworkToHostOrder((long)BitConverter.ToUInt64(bytes));
My understanding is, since both long and ulong are value type, casting between them will not have any boxing or unboxing involved.
I just want to be sure, does the code above have boxing and unboxing involved?
ulong
and long
are both value types. Boxing only occurs if you convert a value type to a reference type.
The source code for NetworkToHostOrder is here. As you can see, no boxing occurs there either; it's just bit operations.
Some weirdness may occur if you use a checked conversion from ulong
to long
that is outside of the range of the long
, because an exception object will be created. But you probably have larger problems at that point.