views:

68

answers:

4

C#: Does Serializable() attribute prevent passing a class instance to another form?

I have the following classes, and is trying to build a settings module for my application. But when i try to access _configurator in settingForm method i get an exception: "object reference not set to an instance of an object". Why?

[Serializable()]
public class Config
{
    public Config() { }
    public string ComPort
    {
        get
        {
            return comPort;
        }
        set
        {
            comPort = value;
        }
    }

    private string comPort;

}

public partial class kineticMoldDockUserControl : UserControl
{

    private settingsForm setForm = null; 

    private Config _cf = null;



    public kineticMoldDockUserControl()
    {
        InitializeComponent();

        _cf = new Config();
        _cf.ComPort = "COM12";

    }




    private void preferencesToolStripMenuItem_Click(object sender, EventArgs e)
    {



        if (!Application.OpenForms.OfType<settingsForm>().Any())
        {

            setForm = new settingsForm();

            setForm.Show();

            setForm.cf = _cf;


        }



    }


}

public partial class settingsForm : Form
{

    Config _configutor = null;
    public Config cf { get { return _configutor; } set { _configutor = value; } }


    public settingsForm()
    {
        InitializeComponent();

        try
        {
            MessageBox.Show(_configutor.ComPort.GetType().ToString());
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

     }

}
+4  A: 

You error has no relation with Serializable attribute. Problem lies in below lines of code:

            setForm = new settingsForm();

            setForm.Show();

            setForm.cf = _cf;

SettingsForm constructor is using configurator but you are setting it after constructor is called. You may pass the configurator via constructor to solve your issue.

VinayC
ok, can you point me in the right direction then?
Bildsoe
@Blidsoe, sorry for that - I have edited my answer.
VinayC
Thanks - do i accept your answer, or can i delete this post, since it is posted in the wrong place?
Bildsoe
+1  A: 

The code you pasted does not work because you access _configurator in the Constructor of settingsForm.

You should instead create a Constructor that accepts a Config instance.

The Serialization Attribute is not the cause of your error.

testalino
A: 

I'm going to go out on a limb and say that's it because you never instantiate your class. Only code I see is:

Config _configutor = null;;

Coding Gorilla
It's assigned in the property setter (the next line of code).
Fredrik Mörk
That's in a user control class though, not his Form class.
Coding Gorilla
+1  A: 

You're trying to display information about the configutor in the constructor, when the cf variable doesn't get set until after you show the form.

David