PJW
PJW

Reputation: 5417

Object reference not set to an instance of an object (custom class as property on a form)

I have a WinForms app.

One of my forms has two properties which are custom classes i.e.

private cContact con;
private cIP ip;

In the LOAD event for the form I initialize these properties as follows -

this.con = new cContact();
this.ip = new cIP();

The parameterless Constructors for these classes simply populate the ID field and nothing else e.g.

class cContact
{
    private int _id;
    //...plus several other properties here

    public cContact()
    {
        this._id = 0;
    }

    public int ID
    {
        get {return this._id;};
        set {this._id = value};
    }
}    

Both classes contain multiple properties of which ID is just one (int).

Both classes contain Get / Set access modifiers for all properties.

Both classes have been in use for over a year without any issues, so I don't think the problem I am having is with the Classes themselves.

Then in my form I have an Event Handler which attempts to access the IDs in the two form properties (my custom classes)

private void Button_Click( . . .)
{
    int myID = this.con.ID
}

Yet I get a message saying

Object reference not set to an instance of an object

As the classes are instantiated in the Form's LOAD event, I fail to see why the button click event handler cannot access the class ID field. Pretty sure this is going to be something simply when one of you point it out, but alas its had me scratching my head for too long already.

Upvotes: 1

Views: 754

Answers (1)

Matthew Watson
Matthew Watson

Reputation: 109862

I suspect what may have happened here is that the Forms designer has serialized the properties into the "Designer.cs" file when you didn't want it to.

This will only happen if the properties are public, though.

If they are public and if you do not want the Forms designer to manage serializing and deserializing the properties' values, you have to use the DesignerSerializationVisibility attribute to tell it not to, like so:

[
    Browsable(false),
    DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]

public MyType MyPropertyWhichMustNotBeSerialized
{
    get;
    set;
}

If this is what has happened, you should be able to see the unwanted serialization in the "Designer.CS" file. You can remove it, and then also add an attribute to the properties as shown above, and you should be ok then.

Upvotes: 2

Related Questions