0

I have this structure:

public class StudentNew
{
    public int StudentId { get; set; }
   ...
}

public class RootObjectNew
{
    public List<StudentNew> StudentsNew { get; set; }
    public int test { get; set; }
}

and I want to set properties to StudentsNew.

RootObjectNew RootObjectNewObject = new RootObjectNew();
RootObject obj = JsonConvert.DeserializeObject<RootObject>(Out);
int i = -1;
foreach (var stu in obj.Students)
{   
    i++;
    RootObjectNewObject.StudentsNew[i].StudentId = stu.Id;
    RootObjectNewObject.test = 123;
}

but get error:

2018-03-03T09:18:55.628 [Info] Compilation succeeded.
2018-03-03T09:18:56.971 [Info] C#************************
2018-03-03T09:18:57.386 [Error] Exception while executing function: Functions.fGetStudentBySkudId. Microsoft.Azure.WebJobs.Script: One or
more errors occurred. f-fGetStudentBySkudId__-2136340708: Object
reference not set to an instance of an object.

If I comment

RootObjectNewObject.StudentsNew[i].StudentId = stu.Id;

I get status = 200 what am I doing wrong???

eocron
  • 5,589
  • 16
  • 40
  • 2
    Please see the duplicate. In short: you're not instantiating the StudentsNew list, you're not adding any instances of student to that list, so trying to call `RootObjectNewObject.StudentsNew` will throw this exception and `RootObjectNewObject.StudentsNew[i]` would throw `IndexOutOfRangeException` even if you created a new instance for the list. – Llama Mar 03 '18 at 09:34
  • 1
    I suggest that you add a break point and step through the code. The error message states that you have a null reference. The debugger will show you which line fails. – Mark Willis Mar 03 '18 at 09:37
  • Sorry, I was wrong in my previous comment. I meant `ArgumentOutOfRangeException`, not `IndexOutOfRangeException`. – Llama Mar 03 '18 at 10:09
  • Don't use `foreach` if you are going to use the index anyway. Just use `for`. Though in this case you shouldn't even need it; you need to _add_ elements. – Nyerguds Mar 05 '18 at 12:53

1 Answers1

2

You must create instance of StudentNew in RootObjectNewObject:

RootObjectNew RootObjectNewObject = new RootObjectNew();
RootObjectNewObject.StudentsNew = new List<StudentNew>();
RootObject obj = JsonConvert.DeserializeObject<RootObject>(Out);
foreach (var stu in obj.Students)
{   
    var st = new StudentNew{
      StudentId=Stu.Id,
      ...
    };
    RootObjectNewObject.StudentsNew.Add(st);

}
Ive
  • 1,251
  • 2
  • 16
  • 22