Replies: 7 comments
-
I wouldn't be surprised if this is optimized out anyways. But the reason is probably that this also allows you to swap values: string left = "two";
string right = "one";
(left, right) = (right, left);
Console.WriteLine("{0} <-> {1}", left, right); |
Beta Was this translation helpful? Give feedback.
-
|
Beta Was this translation helpful? Give feedback.
-
The optimization seems to apply if you are setting a |
Beta Was this translation helpful? Give feedback.
-
Evaluation order is not the same: using System;
class X
{
public int A { get { Console.WriteLine("X.A"); return 0; } }
public int B { get { Console.WriteLine("X.B"); return 0; } }
}
class Y
{
#if tuple
// Y.A → Y.B → X.A → X.B
public Y(X other) => (A, B) = (other.A, other.B);
#else
// Y.A → X.A → Y.B → X.B
public Y(X other)
{
A = other.A;
B = other.B;
}
#endif
private int _a;
private int _b;
public ref int A { get { Console.WriteLine("Y.A"); return ref _a; } }
public ref int B { get { Console.WriteLine("Y.B"); return ref _b; } }
} |
Beta Was this translation helpful? Give feedback.
-
@ufcpp While that's true, it's not the same code that the OP posted, so I'm not sure that it's relevant? |
Beta Was this translation helpful? Give feedback.
-
Even the x86 assembly and IL code in Sharplab for the original code is different. So I was just curious why there's a difference in Sharplab. |
Beta Was this translation helpful? Give feedback.
-
It seems that when fields are accessed as part of a tuple, those fields are always copied to locals. It seems there are some cases that nobody's bothered to optimize - your example is one, this is another: using System;
public class Product
{
public int Id;
public string Name;
public void MethodA()
{
var (a, b) = (Id, Name);
Console.WriteLine($"{a} {b}");
}
} Compiles to two sets of locals: public void MethodA()
{
int num = Id;
string text = nName;
int num2 = num;
string arg = text;
Console.WriteLine(string.Format("{0} {1}", num2, arg));
} I think the relevant code is around here. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
I would expect the two methods below to generate the same code:
But in Sharplab the ValueTuple assignment in MethodA becomes
Bug or by design? The ValueTuple version seems a bit more inefficient?
Beta Was this translation helpful? Give feedback.
All reactions