-6

I have two projects in my solution: HomeworkCalendar (VB.net Windows Forms Application) and HWLib (C# .dll Class Library). In the CurrentUser class in the library I have a variable defines as HWLib.User currentUser. This comes from the User class in HWLib:

namespace HWLib
{
    public class User
    {
        /// <summary>
        /// The Name of the User
        /// </summary>
        public String name = null;
        /// <summary>
        /// The Age of the User
        /// </summary>
        public int age = 0;
        /// <summary>
        /// The School Type of the User
        /// </summary>
        public String school = null;
        /// <summary>
        /// The Amount of Classes the User
        /// </summary>
        public int classesCount = 0;
        /// <summary>
        /// The String Array that holds all the classes
        /// </summary>
        public string[] classes;
    }
 }

Here is as it is in the CurrentUser class

public class CurrentUser
{
    /// <summary>
    /// The current User using the program
    /// </summary>
    public static HWLib.User currentUser;
}

So I attempted to store the user information into this variable, but this is where I get a NullReferenceException

Try
    If intClasses <= 11 Then
        CurrentUser.currentUser.name = txtName.Text
        CurrentUser.currentUser.classesCount = intClasses
        CurrentUser.currentUser.school = cboSchool.SelectedItem
        CurrentUser.currentUser.age = Convert.ToInt32(cboAge.SelectedItem)
    End if
Catch exx As NullReferenceException
   'It does catch! This is the issue! Why does it catch here and how do I fix it?
    File.Delete(Base.filePath)
    MsgBox(exx.ToString())
End Try
user2678408
  • 117
  • 1
  • 2
  • 14

1 Answers1

2

Well, to get it to run you'll need to initialize currentUser:

public class CurrentUser
{
    /// <summary>
    /// The current User using the program
    /// </summary>
    public static HWLib.User currentUser = new HWLib.User() ;
}

but:

  1. Why do you have a non-static class with just a static property? Just make CurrentUser static
  2. It is a better practice to use properties (with getters/setters) instead of fields. THat allows you to add logic to the get/set without breaking client code.
D Stanley
  • 139,271
  • 11
  • 154
  • 219