Pattern Matching is not side-effect free. Why must the pattern itself be constant then? #4321
-
I realized that pattern matching can cause side effects when Property Getters do stuff: record MyRec
{
string _prop;
public string Prop
{
get
{
Console.WriteLine("hello");
return _prop;
}
set { _prop = value; }
}
} running a pattern like In that light, it seems strange to me that patterns must be constant, e.g. this will give an error: var s = "someString";
var a1 = myRec is MyRec { Prop: s }; // CS0150: A constant value is expected Is there a good reason for this ... errr ... inconsistency? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
Our recommendation is that your properties not cause side effects. Yes, they can, and we can't break 20 years of history and forbid it now. But given how we process patterns, small changes in pattern ordering can change how many times a particular property is accessed and can have unpredictable results. We don't want to enable the same for the other side too. |
Beta Was this translation helpful? Give feedback.
-
I think the real question is should we have pattern that match against value of variable. I also brought it up in the past. I think it would be valuable in C# because using patten matching in This is what I thought people would do. Try to use variable in place of pattern and get this "CS0150: A constant value is expected" error. So maybe it's worth it to consider allowing it. |
Beta Was this translation helpful? Give feedback.
Our recommendation is that your properties not cause side effects. Yes, they can, and we can't break 20 years of history and forbid it now. But given how we process patterns, small changes in pattern ordering can change how many times a particular property is accessed and can have unpredictable results. We don't want to enable the same for the other side too.