In this example, i am able to create new student object and able to add data to its 2 variables called Id and Name but i am facing difficulty and not able to add third variable (List -> i.e. friends)
using System;
using System. LINQ;
using System. Collections. Generic;
public class Program
{
//public List<Student> students;
public static void Main()
{
var students = new List<Student>();
students. Add(new Student
{
Id = 120228,
Name = "Rajesh",
});
students. Add(new Student
{
Id = 120229,
Name = "Mahesh",
});
foreach(var student in students)
Console. WriteLine(student.Id + ", " +student.Name);
}
}
public class Student
{
public int Id;
public string Name;
public List<Friend> friends;
}
public class Friend {
public int friendId;
public string friendName;
}
How should i add data to "friends"(List<Friend>) variable like other first 2 fields. (if possible help me with working code)
//finally, i want to print all details of the student.
foreach(var student in students){
foreach(var friend in student.friends){
Console. WriteLine(student.Name+ " friend name is " +friend.Name);
}
}
Thank you for your valuable time!!
NullReferenceExceptionon fieldfriends?List<Friend> friendsanywhere I can see. Either do it in the constructor forStudent, or do it somewhere else once you've created theStudentobject