C # - Link to "this int" parameter



I have very simple bitwise working methods that I want to use as follows:

myInt.SetBit(int k, bool set)

so that it changes the bit in the index "k" to the value "set" (0 or 1), I first thought about how to do this as follows:

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 the variable "A", and not the original variable, since the integer is not a reference type.
I cannot use 'ref' with 'this', so I don’t know how to turn this into a reference parameter.
I already have similar methods for Int arrays, but they work just fine since the array is a reference type.

I am looking for a way to preserve this convenient syntax for single integers, if any.

+4
source share
5 answers

I suggest simply returning the result instead of trying to change the 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);
+1

.

. . String.Replace, , .

public static int SetBit(this int A, int k, bool set)
{
    if (set) A |= 1 << k;
    else A &= ~(1 << k);

    return A;
}
+5

(, int s) , , . , , int, int .

:

public static int SetBit(this int A, int k, bool set) { 
    if (set) A |= 1 << k; 
    else A &= ~(1 << k); 
    return A;
}

:

var x = 5;
x = x.SetBit(1, true);
+4

, . , ref.

. , - .

0

You can not mix thisand refin extension methods. You have many options:

  • Returning the result from the extension method (I prefer this option):

    public static int SetBit(this int A, int k, bool set)
    {
        if (set) A |= 1 << k;
        else A &= ~(1 << k);
    
        return A;
    }
    

    via:

    int i = 3;       
    i = i.SetBit(1, false); 
    
  • Using method with ref:

    public static void SetBitRef(ref int A, int k, bool set)
    {
        if (set) A |= 1 << k;
        else A &= ~(1 << k);
    }
    

    using:

        int i = 3;
        IntExtensions.SetBitRef(ref i, 1, false);
    
  • Using the IntWrapper class instead of int:

        class IntWrapper
        {
            public IntWrapper(int intValue)
            {
                Value = intValue;
            }
    
            public int Value { get; set; }
        }
    

    with a reference type, you can create this extension method:

    public static void SetBit(this IntWrapper A, int k, bool set)
    {
        int intValue = A.Value;
    
        if (set) intValue |= 1 << k;
        else intValue &= ~(1 << k);
    
        A.Value = intValue;
    }
    

    via:

    IntWrapper iw = new IntWrapper(3);
    iw.SetBit(1, false);
    
0
source

Source: https://habr.com/ru/post/1651406/


All Articles