0

I have a class like below. When I'm assigning values to it , It shows "Object reference not set to an instance of an object"

public class Student
{
    public string Name{ get; set; }
    public string SurName { get; set; }        
    public List<Score> Scores { get; set; }
}
public class Score
{
    public string Subject { get; set; }
    public string Grade { get; set; }
}

And using below code I'm assigning values to it,

                Student obj = new Student();
                string sql = "SELECT student_name, student_surname dv_students  where a.User_id=@User_id";
                SqlCommand cmd new SqlCommand(sql,con);
                cmd.CommandType = CommandType.Text;
                cmd.Parameters.AddWithValue("@User_id","S1234");
                SqlDataReader dr = cmd.ExecuteReader();
                if (dr.HasRows) {
                    while (dr.Read())
                    {
                        obj.Name = Convert.ToString(dr["student_name"]);
                        obj.SurName = (string)dr["student_surname"];
             List<Score> Scores = new List<Score>();
                     int k = 0;
                        foreach (SubmissionDetail SubmissionDetails in objSubmission.SubmissionDetails)
                        {                           
                               Scores[k].Subject= SubmissionDetails.Subject;//getting exception here
                                Scores[k].Grade= SubmissionDetails.Grade;

                                k++;
                            }
       obj.Scores = Scores;
                        }}}
Sajith
  • 93
  • 2
  • 10
  • 2
    Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – nalka Jan 31 '20 at 09:07
  • 2
    Your `List Scores` is not instantiated. Add `= new List();` after it. – Philippe B. Jan 31 '20 at 09:08
  • @PhilippeB. Please see my edited question. Now I got Index was out of range. Must be non-negative and less than the size of the collection. – Sajith Jan 31 '20 at 09:32
  • You don't seem to understand what you are doing. I would suggest that you take some C# tutorial and some OOP tutorials too. Anyway, you have a `List<>` why do you use it as an array ? Even if it is possible and can be usefull in some situations there is no point here doing it so. You must create a new `Score` object, set its two properties `Subject` and `Grade` to your values in your foreach and add your newly created `Score` object to your `List`. – Philippe B. Jan 31 '20 at 19:19
  • `Score score = new Score();` `score.Subject = submissionDetails.Subject;` `score.Grade = submissionDetails.Grade;` `Scores.add(score);` You can even do better and create a constructor in your `Score` object. – Philippe B. Jan 31 '20 at 19:20

0 Answers0