Levi H
Levi H

Reputation: 3586

Property is getting set to null after I set it to something?

I've got a custom control and one of the properties is:

public List<SelectionBox> Boxes { get; set; }

In the control constructor I have:

this.Boxes = new List<SelectionBox>();
this.Boxes.Add(new SelectionBox("", Color.Red));

Before InitializeComponent(), if I do a breakpoint here it shows that Boxes is a list of SelectionBox with 1 element. But then inside of my OnPaint override it has been set to null with some weird behaviour, if I do the following:

foreach (SelectionBox box in Boxes) {}

It doesn't throw an error it just exits the function by there. What am I doing wrong?

Selection box struct:

[Serializable]
public struct SelectionBox
{
    public string Name;
    public Color Colour;
    public Rectangle BoxRectangle;
    public bool IsActive;

    public SelectionBox(string name, Color colour)
    {
        this.Name = name;
        this.Colour = colour;
        this.IsActive = false;
        this.BoxRectangle = new Rectangle(0, 0, 0, 0);
    }
}

Upvotes: 0

Views: 1389

Answers (1)

Robert Levy
Robert Levy

Reputation: 29083

If you need to track down how a property is mysteriously getting its value set to null, rewrite the property with explicit get/set implementations, drop a breakpoint in the setter, and check out the callstack when the breakpoint is hit

private List<SelectionBox> _boxes;
public List<SelectionBox> Boxes { get { return _boxes; } set { _boxes = value; } }

Upvotes: 1

Related Questions