Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top