I have a common problem where the order of operations is not respected when using the ? or ?? operators. In the following code, the programmer intended to set price to bigPrice + 5, defaulting bigPrice to 0 if it is null.
var price = bigPrice ?? 0 + 5;
Obviously the order of operations for the ?? operator evaluates the entire expression to the right as the argument, but it is a common mistake. Is it possible to alleviate this with a resharper quick fix / structural find and replace, essentially requiring parenthesis around your ?? statements? I've tried, but can't get a macro that identifies multi part arguments (0 + 5).
I'd like to know if this is possible / what the best way to do this is.
You could do a find and replace
in Visual Studio using regular expression,
In the find-replace dialog (Ctrl+H), enter the following,
Find what: {:i:b??:b:z:b}{[+-/*]:b:z};
Replace with: (\\1) \\2;
Look in: Current project
Initial code,
var price = bigPrice ?? 0 + 5;
After replacement,
var price = (bigPrice ?? 0 ) + 5;
A quick explaination of the find and replace expressions,
Find Expression: {:i:b??:b:z:b}{[+-/*]:b:z};
: {xxx}
represents tagged expression ie it is a grouping of the expression found. :z
stands for integer, :b
stands for blank space, :i
stands for identifier. [xxx]
stands for any character in the set. And \\
is used to escape special characters. So in your case tagExpression1
evaluates to bigPrice ?? 0
bigPrice ?? 0
while tagExpression2
evaluates to + 5
.
Replace expression: (\\1) \\2;
: \\1
stands for first tag expression and \\2
stands for the second tag expression. The expression results in (
)
being placed around the first tag expression followed by a blank space and then the second tag expression.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.