How to refactor this decompiled C# code with invalid reference syntax?
Solution 1:
This is one of those things that dotPeek fails on but ILSpy handles nicely. What you're seeing is a compiler optimization of the +=
operator. Rather than calculate the field location twice - once to fetch the value and again to store it - the compiler generates code that calculates the field offset one time then uses it for both parts of the operation.
The bit you're having trouble with (the unknown ^
operator) is most likely an attempt by dotPeek to show a dereference of the ref variable. Of course this isn't necessary in C# where we just use the name of the variable itself.
Just rewrite it as:
m_position += byteCount;
The compiler will decide whether or not it wants to add that particular optimization in.
Solution 2:
long&
represents a reference type for a long and should be replaced with ref long
. It’s then assigning the address of the m_position
field to the local
variable (making local
an alias for it), then checking for arithmetic overflow when adding the byte count to it. Not entirely sure about the caret, in managed C++ it’s a hat to instruct for GC of object, so I suppose that’s what it’s doing. When the arithmetic check completes successfully, the m_position
field via local
var is set to the current value plus byteCount
.
ref long local = ref this.m_position;
long num = checked(local + (long)byteCount);
local = num;