views:

305

answers:

3

I'm a little confused about when exactly my Property is being initialized.

Suppose I have a property declared like this:

private Dictionary<string, Dictionary<string,string>> MessageLookup
    {
        get
        {
           return messages ?? doSomething();
        }
    }

The doSomething method populates the messages Dictionary and returns it.

My question is, when is this code run? If I place a breakpoint into the doSomething code, it isn't hit, but the MessageLookup property is holding data (this is the only place it is initialized) when I view it in the debugger.

Is this code run at construction? does the debugger run it automatically when I hover over the variable name? If so, why isn't the breakpoint hit?

A: 

It is run when your property is first evaluated. No background stuff going on.

I'm guessing you're not seeing this because you use Quickwatch to inspect your object. At that point it will get executed and your breakpoint will be skipped.

Thorarin
+5  A: 

That code is run whenever anyone refers to the property, and not before.

If you use the debugger, you'll see it because the debugger tries to fetch property values automatically (so you can see the state of the object). I don't know whether the debugger ignores breakpoints while it's evaluating properties for itself - that would explain everything.

Try running your code not in a debugger, and make some code access your property:

var lookup = someObject.MessageLookup;

Make doSomething() dump a stack trace and you'll see what's going on.

Jon Skeet
Just to make sure I'm getting this...The debugger will not hit breakpoints in doSomething if it does the automatic fetch?
SP
The debugger ignores everything, including sanity, during func eval. http://blogs.msdn.com/jmstall/archive/2007/03/13/func-eval-abort-is-evil.aspx
280Z28
@Me: I love func eval. I just make sure my pure methods (including the ones the debugger assumes are pure) behave themselves and it's never an issue.
280Z28
Depending on the debugger, he could bypass some of these issues by using things like `DebuggerHidden` and other such attributes from the `System.Diagnostics` namespace (i.e. debugger will ignore and not automatically evaluate these properties), allowing him to still use the debugger and step into his code w/o having to do the stack trace.
Erich Mirabal
A: 

Property getters (and ToString() for that matter) are assumed to be pure, which basically means evaluating it has no side effects. You should rewrite the code to adhere to that assumption or you'll face nasty consequences. If must use lazy initialization at access time, use a GetMessageLookup() method instead.

280Z28