Shubham Bhewanewala Shubham Bhewanewala - 10 months ago 58
ASP.NET (C#) Question

Array instantiation of an object

public class Teacher{
public string imageUrl;
public TeacherEducationalQualification[] teacherEducationalQualification;

public class TeacherEducationalQualification{
public string NameOfDegree;
public string NameOfUniversity;
public int YearOfGraduation;

In the above codes when I instantiate Teacher class like

Teacher teacher= new Teacher();

This works fine but when I instantiate array in Teacher class for object 'teacher'

teacher.teacherEducationalQualification = new TeacherEducationalQualification[5];

It gives me an error 'Object reference not set to an instance of an object' whenever i try to access any variable to set values in it.

teacher.teacherEducationalQualification[1].NameOfDegree= "abc";

Please Help.

Answer Source

After you initialize an array of objects (reference type) its items will be null. You have to iterate (loop) through the array and initialize each item.

If you want to set each item individually however, you can do something like this

Teacher teacher = new Teacher();

teacher.teacherEducationalQualification = new TeacherEducationalQualification[5];

// Initialize item at index 0; indices start with 0 so the 1st item has index 0
teacher.teacherEducationalQualification[0] = new TeacherEducationalQualification();
teacher.teacherEducationalQualification[0].NameOfDegree= "abc";

// Initialize item at index 1

// Initialize item at index 2

// Initialize item at index 3

// Initialize item at index 4; this is the last index, your 5th item
teacher.teacherEducationalQualification[4] = new TeacherEducationalQualification();
teacher.teacherEducationalQualification[4].NameOfDegree= "xyz";

// Or in a different way with the help of a local variable
var qualification;

qualification = new TeacherEducationalQualification();
qualification.NameOfDegree= "abc";
// set other fields
teacher.teacherEducationalQualification[0] = qualification;

// ...

qualification = new TeacherEducationalQualification();
qualification.NameOfDegree= "xyz";
// set other fields
teacher.teacherEducationalQualification[4] = qualification; // last item

Note: field names in C# should be camelCase - start with a lowercase letter

public string nameOfDegree;

Properties, on the other hand, should be PascalCase - start with an uppercase letter

public string NameOfDegree { get; set; } // auto-implemented property