Click here to Skip to main content
15,991,071 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Can we have a Generic properties?I have a requirement of storing the data.So i have taken class with Generic Properties.When i add the data to that Property am getting an error that "Object reference not set to an instance of an object" .please suggest me some idea.
class GeneralClass
    {
        private List<int> _student_rollnumber;
        public List<string> _student_name;
        public List<int> Student_RollNumber
        {
            get { return _student_rollnumber; }
            set { _student_rollnumber = value; }
        }
        public List<string> Student_Name
        {
            get { return _student_name; }
            set { _student_name = value; }
        }
    }


i have used the Class in Button Click.
private void btn_save_Click(object sender, EventArgs e)
      {
          try
          {
              GeneralClass obj = new GeneralClass();
              obj.Student_RollNumber.Add(int.Parse(txtbx_rollnum.Text));
              obj.Student_Name.Add(txtbx_SName.Text);
              MessageBox.Show("Data saved");
          }
          catch (Exception ex)
          {
              MessageBox.Show(ex.Message, "Message from form");
          }
      }
Posted

1 solution

You need to assign an instance of your lists to each of the lists you are trying to use, as in:
private List<int> _student_rollnumber = new List<int>();

If you don't then when you try to use them you will get a null reference exception.
Additionally, don't use public on internal fields - it exposes your code internals to the outside world, and fixes you to use that for the rest of time. Instead, provide public properties and methods to manipulate internal data - that way you can change how you store information without changing the working code that uses your class.

By the way, I would have a class Student which had a roll number, and a name, then then set up a list of Students - that way the Student can take care of itself, it doesn't need to know other students even exist, much less how they are stored.

[edit]HTML characters fixed greater than disappearance.![/edit]
 
Share this answer
 
v2
Comments
hemantwithu 14-Sep-10 6:08am    
Thank you

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900