Skip to content Skip to sidebar Skip to footer

Trouble Understanding Pass By Reference

I find it really confusing to understand pass by reference in c#. In my code I have function which takes two parameters private bool SerialUnEscape(byte serialData, ref byte seria

Solution 1:

If you really want to imitate pass-by-reference instead of changing your code to return the value, you can wrap the primitive you want to change in an object. For simplicity, I used a list:

defchange_reference(byteContainer):
    byteContainer[0] = 42

b = 123print(b) # Prints 123# Copy the data into the container list.
container = [b]
# Pass a pointer to that list into the function.
change_reference(container)
# Take the value out of the container.
b = container[0]

print(b) # Prints 42

This makes your function really confusing though. What you should really do is include the modified byte in the return value:

deftest_and_subtract(v):
    if v == 1:
        return (v - 1, True)
    return (v - 2, False)

v = 1
v, b = test_and_subtract(v)
print(v) # 0print(b) # True

v = 5
v, b = test_and_subtract(v)
print(v) # 3print(b) # False

Here return (v - 1, True) is putting both results into a tuple, and b, v is removing them from that tuple.

Post a Comment for "Trouble Understanding Pass By Reference"