Weird behaviour with conditional operator in .Net
This has me pretty stumped. Maybe I'm too tired right now.
Rectang开发者_如何学Cle rectangle = new Rectangle(0, 0, image.Width, image.Height);
Rectangle cropArea = inputArea == null ? rectangle : inputArea.Value;
if (inputArea == null)
cropArea = rectangle;
inputArea is a nullable Rectangle, which in my particular case is null.
The first two statements yields a cropArea initialized to 0. The second, however, yields the correct cropArea based on the image width and height. Have I misunderstood anything with the conditional operator? It seems it does not return rectangle when inputArea = null? Is there any quirks when working with value types?
EDIT: Alright, I should have tried this first: restarted VS. It seems the debugger lied to me, or something. Anyway, works now. Thanks.
That seems like a nasty bug in Visual Studio debug mode which is fooling you:
Now F10 to step over this line and you get:
On the console correct values are printed.
WTF.
Rectangle cropArea = (!inputArea.HasValue) ? rectangle : inputArea.Value;
So are you saying that when inputArea
is null
, without the if
statement you get a rectangle initialized to something else than the image size? I just tried running that and it works fine. Make sure that image
has a size and that inputArea
is actually null
.
Your code appears correct. The conditional expression (or conditional operator, or originally called the ternary operator... everyone happy now? :)) should be interchangeable with if/else statements.
Rectangle cropArea = inputArea == null ? rectangle : inputArea.Value;
should be exactly the same as:
Rectangle cropArea;
if (inputArea == null)
{
cropArea = rectangle;
}
else
{
cropArea = inputArea.Value;
}
(in fact they should generate the same IL code).
Trace through with the debugger and see if anything jumps out at you.
What the hell?
Rectangle rectangle = ...;
Rectangle cropArea;
if (inputArea == null)
cropArea = rectangle;
else
cropArea = inputArea.Value;
if (inputArea == null)
cropArea = rectangle;
Why have the second if? It's totally and entirely redundant. The scenario in which cropArea might still be null or zero is if inputArea.Value is null/zero, since you didn't check for that (only if inputArea is null).
精彩评论