Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Referencing "this int" parameter



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.

like image 846
grr Avatar asked Dec 25 '22 02:12

grr


1 Answers

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;
}
like image 131
Habib Avatar answered Jan 06 '23 10:01

Habib