-2

Right now I can do this:

public static void Swapper (ref int a, ref int b) {
       b = (a = a + b) - b;
       a = a - b;
}

But I want to be able to do this:

public static void Swapper (ref int a, ref int b) {
      a = (b = a);
}

So, I want the assignment expression to return the original value of the left operand before it gets changed. This is a syntax-related question, and I'm looking for a general solution that works for all cases, not just the specific example provided. Is this possible?

Edit

I'm aware of:

(a, b) = (b, a);

This specific case is just an example used to illustrate what I want syntax-wise. Is just a dummy method. I don't have a need to swap two variables.

Basically I have ++i and I want i++.

Edit 2

In Python the functionality for returning the value in an assignment expression is achieved by the walrus operator :=. Let's assume this new operator that returns the left-hand side first is expressed like =:, a reverse walrus operator.

Then when traversing some kind of linked list, for example, we could do (in C#):

while (x != null && y != null) {
    node = (node.next = (x.value > y.value) ? new Node(x =: x.next) : new Node(y =: y.next));
}

vs

while (x != null && y != null) {
    if (x.value > y.value) {
        node = (node.next = new Node(x));
        x = x.next;
    } else {
        node = (node.next = new Node(y));
        y = y.next;
    }
}

Anyway, this is probably convoluted and rarely useful, but seems a bit more elegant to me.

gabriel
  • 153
  • 1
  • 10
  • Why not `(a, b) = (b, a);` to swap values? – Dmitry Bychenko Apr 29 '23 at 13:12
  • 1
    The basic idea of line-of-business languages such as C# is to *clearly communicate the algorithm to the reader of the code*, not to make tiny puzzle boxes that the reader has to figure out. Can you say a little more about what problem you're actually trying to solve here? If you want the value of a variable before the variable is modified, *store it in a local*. Naming storage of temporary values is the whole *purpose* of having locals in the first place. – Eric Lippert Apr 30 '23 at 17:09

2 Answers2

0

you can use tuple to swap values: tuple

public static void Swapper(ref int a, ref int b)
{
    (a, b) = (b, a);
}
Hossein Sabziani
  • 1
  • 2
  • 15
  • 20
0

What you're asking for isn't possible.

From the C# spec: "The result of a simple assignment expression is the value assigned to the left operand. The result has the same type as the left operand and is always classified as a value."

This is paraphrased in Microsoft's C# documentation here.

So the result of (b = a) will be the value assigned to b. It isn't possible for this assignment expression somehow to return the original of value of b.

I would strongly recommend reading Eric Lippert's answer here. (And anything else you can find by Eric Lippert on this or any other topic.)

Neil T
  • 1,794
  • 1
  • 12
  • 21