C
C#2y ago
palapapa

✅ `with` expression does not work with `ValueTuple`

This code:
Foo foo = new();
Foo foo1 = foo with { Bar.Item1 = 1 };

record Foo
{
public (int, int) Bar = (0, 0);
}
Foo foo = new();
Foo foo1 = foo with { Bar.Item1 = 1 };

record Foo
{
public (int, int) Bar = (0, 0);
}
Gives The name 'Bar' does not exist in the current context on the second line? Why is this?
6 Replies
Thinker
Thinker2y ago
Bar is a field, not a property I assume with expressions only work with properties...? Or wait might be that you can't set tuple values like that
333fred
333fred2y ago
With expressions do not allow setting nested values
palapapa
palapapa2y ago
Probably because if Bar is a reference type, then with becomes destructive, which is not what it promises
333fred
333fred2y ago
Not really, we didn't allow it because we don't find it clear In this particular example, it's probably ok, but in general we didn't think so There are proposals around enhancements, but they also run into the issue of understandablility
Thinker
Thinker2y ago
You could probably do foo with { Bar = foo.Bar with { Item1 = 1 } }...?
palapapa
palapapa2y ago
I can