0

So im getting this error and i dont quite understand why im getting it. i have tried looking here for answers, but every problem is so unique that they do not apply to my problem.

Here is what i have so far.

class customer{
    public string sFirstName { get; set; }
    public string sLastName { get; set; }
    public int iAge { get; set; }
}
class customerObject{
    public static List<customer> lstStaticUsers { get; set; }
    public customerObject(){
        lstStaticcustomer = new List<customer>();
    }
    public static void AddNewStaticUser(string FirstName, string LastName, int Age)
    {
        lstStaticcustomer.Add(new customer{sFirstName = FirstName, sLastName = LastName, iAge = Age});
    }
}

Here is my window

public partial class wndCustomerInfo : Window
{
    public wndCustomerInfo ()
    {
        InitializeComponent();
    }

    private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    {
        this.Hide();
        e.Cancel = true;
    }

    private void btnSubmitForm_Click(object sender, RoutedEventArgs e)
    {
        customerObject.AddNewStaticcustomer(txtFirstName.Text, txtLastName.Text, Convert.ToInt32(txtAge.Text));
        lblMessage.Content = "Created new user: " + txtFirstName.Text;
    }
}

then here is my main window that opens the one above

public partial class MainWindow : Window
{

    wndCustomerInfo wndCustomerInfoForm;

    public MainWindow()
    {
        InitializeComponent();
        Application.Current.ShutdownMode = ShutdownMode.OnMainWindowClose;
        wndCustomerInfoForm= new wndCustomerInfo ();
    }

    private void btnSave_Click(object sender, RoutedEventArgs e)
    {
        this.Hide();
        wndCustomerInfoForm.ShowDialog();
        this.Show();
    }
}

If anyone could help that would be great. im kind of new to c# so please be nice

Doctor06
  • 677
  • 1
  • 13
  • 28
  • possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – nvoigt Mar 07 '14 at 05:50

1 Answers1

4

Make customObject's constructor static:

static customerObject(){
    lstStaticcustomer = new List<customer>();
}
MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
  • i tired that and i get this error. it wont even complie "access modifiers are not allowed on static constructors" – Doctor06 Mar 07 '14 at 05:56
  • yeah that worked! thank you! other errors like this mean that i need to instantiate the static class. could you explain why what you did worked? and why i dont need to instantiate it now? – Doctor06 Mar 07 '14 at 06:02
  • Standard, instance constructor runs whenever you create new instance of class. `static` constructor runs automatically only once, before your class is used for the first time. That's why you should use static constructor to initialize static fields/properties. – MarcinJuraszek Mar 07 '14 at 06:06