Strange behavior with conditional statement in .Net

This is pretty strong with me. Maybe I'm too tired right now.

Rectangle rectangle = new Rectangle(0, 0, image.Width, image.Height); Rectangle cropArea = inputArea == null ? rectangle : inputArea.Value; if (inputArea == null) cropArea = rectangle; 

inputArea is the null rectangle, which in my particular case is null.

The first two operators give the cropArea property, initialized to 0. The second, however, gives the correct cropArea function based on the width and height of the image. I did not understand something with the conditional statement? It doesn't seem to return a rectangle when inputArea = null? Are there any quirks when dealing with type values?

EDIT: Well, I should have tried this first: restarted VS. The debugger seems to be lying to me or something like that. In any case, it works now. Thanks.

+7
c # conditional-operator nullable value-type
source share
5 answers

This seems like a nasty bug in the debugging mode of Visual Studio that is fooling you:

alt text

Now F10 go on this line and you will get:

alt text

The correct values ​​are printed on the console.

WTF.

+1
source share
 Rectangle cropArea = (!inputArea.HasValue) ? rectangle : inputArea.Value; 
0
source share

Your code is displayed correctly. A conditional expression (or a conditional operator, or originally called a ternary operator ... is everyone happy now? :)) should be used interchangeably 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 must generate the same IL code).

Track with the debugger and see if anything pops up.

0
source share

So you say that when inputArea is null , without an if you get a rectangle initialized with something other than the size of the image? I just tried to run this and it works fine. Make sure image is sized and inputArea is actually null .

0
source share

What the heck?

 Rectangle rectangle = ...; Rectangle cropArea; if (inputArea == null) cropArea = rectangle; else cropArea = inputArea.Value; if (inputArea == null) cropArea = rectangle; 

Why does the second one have? This is completely and completely redundant. The scenario where cropArea can still be null or null is if inputArea.Value is null / zero since you did not check it (only if inputArea is null).

-one
source share

All Articles