Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decimal Ternary Not Working

Tags:

c#

I'm trying to use a ternary to assign a decimal type. It's not working for me. Am I going crazy?

Here's a screen shot of my debug. You can see the value of everything before I step. enter image description here

And after I step here is the value. It isn't even one of the viable options (i.e. 1 or 2000). enter image description here

Is there some strange limitation with decimals that I don't know about? When I break it out into its full if/else logical representation it works fine. The only thing I can guess is that I did recently install .NET Framework 4.5.

UPDATE

I've cleaned the solution and made sure I was running on code that was compiled in debug mode as recommended in the comments. Neither of those seemed to change anything.

I started to get curious though when I noticed all my unit tests were still passing. After a little more sleuthing I found that when I stepped one more time (i.e. stepped over memberItems.Add) price magically has the right value in it.

Does .Net do some kind of a delayed resolution of ternary operators similar to the yield command in iterator blocks? I've never noticed it before now but I don't know what else it could be. I suppose I could also still be running on code compiled in release mode accidentally. I've made dumber mistakes after triple checking myself.

like image 594
Mark Rucker Avatar asked Aug 22 '12 13:08

Mark Rucker


1 Answers

Impossible to diagnose code from a screenshot, so just a guess.

You cannot always completely rely on what a watch expression tells you. The first possible failure mode is debugging code that was optimized. A local variable like price will very typically be optimized by the jitter optimizer to be stored in a cpu register instead of the stack. The watch expression will show you the stack location value, not the cpu register value. With 0 being a common result. The only real defense you have against this is only debugging code that was built by the Debug configuration.

Second failure mode is the way watch expressions are evaluated. The CLR starts a dedicated thread when it detects an attached debugger. The debugger can then use this thread to evaluate watch expressions. This can go wrong if a variable has any thread affinity. Common cases are variables that are [ThreadStatic] or are properties of COM objects.

like image 105
Hans Passant Avatar answered Oct 30 '22 18:10

Hans Passant