Value replacement expression; generalized form of ?? #4594
-
PreambleVery simple idea, and I have no idea for a good syntax but consider the following case: // someValue is a parameter in a method and is of type int
someValue = (someValue == -1 ? 100 : someValue); Although this can be condensed using: // someValue is a parameter in a method and is now of type (int?)
someValue ??= 100; The type of the variable has now been changed, meaning direct access to the value of ProposalIn order to mitigate this, a "value substitution operator" could be implemented: // someValue is a parameter in a method and is of type int
someValue = (someValue !! -1 ? 100);
// Value replacement syntax; parens are not required.
// (a !! b ? c) evaluates to (a == b ? c : a) When replacing the default value of a type, // someValue = (someValue !! default ? 100);
someValue = (some !! ? 100); Example codepublic float SafeFloatDivide(float num, float den)
{
den = (den !! ? 0.01f);
return num / den;
}
public string EmptyCheck(string str)
{
return str !! "" ? "(empty)";
} Could this be useful / common enough to be considered? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 9 replies
-
IMO the ternary conditional operator is sufficiently terse in these cases. |
Beta Was this translation helpful? Give feedback.
IMO the ternary conditional operator is sufficiently terse in these cases.