grr grr - 2 months ago 6
C# Question

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.


I suggest just returning the result instead of trying to change immutable int:

  // int instead of void
  public static int SetBit(this int A, int k, bool set) { 
    return set ? (A | (1 << k)) : (A & (~(1 << k))); 

So you can do

  int source = 12345;
  int result = source.SetBit(3, true);