I have very simple Bitwise Operator methods that I want to use like this:
myInt.SetBit(int k, bool set)
so that it changes the bit at index 'k' to the value 'set' (0 or 1) I first thought of doing it like this:
public static void SetBit(this int A, int k, bool set) {
if (set) A |= 1 << k;
else A &= ~(1 << k);
}
but of course this only changes the internal value of variable 'A', and not the original variable, since integer isn't a reference type.
I can't use 'ref' along with 'this' so I don't know how to turn this into a reference parameter.
I already have similar methods for Int arrays, but those work fine since an array is a reference type.
I'm looking for a way to keep this handy syntax for single integers, if there is one.
You shouldn't treat it as a reference type.
Make your method return the modified value and assign it back to your variable. That approach will be consistent to immutable types. Consider example of String.Replace
, it doesn't modify the string in place, instead it returns a modified copy.
public static int SetBit(this int A, int k, bool set)
{
if (set) A |= 1 << k;
else A &= ~(1 << k);
return A;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With