Riddle me thisString outputs
time to read 1 min | 108 words
What would be the result of this?
public string Wrap(string x, string y) { return "[" + x ?? y + "]"; }
Can you see the bug?
More posts in "Riddle me this" series:
- (12 Oct 2010) File access & Multi threading
- (06 May 2010) String outputs
- (02 May 2010) Hard links & file moves
Comments
Both x and y can be null, which means the output will be "[]"?
I'll receive an exception when both x and y are null.
You'd end up with either "[" or "[value-of-x" depending on if x is null.
the "[" + x operation will be processed before the ?? operation?
I'm guessing operator precedence. It should be "[" + (x ?? y) + "]".
Nice one.
First guess is that the operator + has a higher priority than the operator ?? and ("[" +x) is always != null and the second part is never used.
I'd say you'd probably want to put the 'x ?? y' into parantheses. The first expression is never null.
Operator precedence? It won't wrap but prefix and always ignore y.
That why I use String.Format:
public string Wrap(string x, string y)
{
return string.Format("[{0}]", x ?? y);
}
I think that's the first one I've been able to get!
Interestingly the ?? is not mentioned on the MS operator prescendece page: http://msdn.microsoft.com/en-us/library/aa691323(VS.71).aspx
@Chris - because 7.1 is the .NET 1.1 documentation. In the current spec this table is 7.3.1, and it is very low in the table; almost anything trumps null-coalescing.
+1 for operator precedence
isn't there an extra problem, what if y is also null?
public string Wrap(string x, string y)
{
return "[" + (x ?? y) + "]";
}
could cause a bug when both x and y are null :)
Its the same that:
public string Wrap(string x, string y)
{
return ("[" + x) ?? (y + "]");
}
Refactoring:
public string Wrap(string x, string y)
{
return "[" + x;
}
?? will never fail the null check because each side of the operation has a bracket concatenated to it.
All the code after x will be ignored !
The output should be "[x"
The code will throw an exception if both x and y are null (you cannot add a string to null). Otherwise, it will be x's value (if not null, y's value otherwise) surrounded by '[' and ']'. Nice bug and not something easily caught if you have a thousand other line to write ASAP.
My guess is what James Gregory said--operator precedence bug.
Has got a tiny bit of "Ouch", though...
It follows the phrase that my Math teacher taught me in 9th grade for determining order or operations.
Please Excuse My Dear Aunt Sally
Parens
Exponentials
Multiplication
Division
Addition
Subtraction
Then everything else.
So it would be
if x is null it is
"["
if y is null it is
"[x"
if both are null it is
"["
I made a mistake, my answer is wrong.
Yeah I had this one in production. I was really surprised, I think it's pretty intuitive to expect ?? being the highest priority...
Comment preview