Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I Initialize an array in class?

public class DataClass
{
    public int[] collectionData;
}

[SerializeField] private DataClass[] DataClassArray;

I have created above field in which class consists of an array, and the object of that class is also an array.

public void GenerateCategariesData()
{
    Debug.Log("==========>******" + bookCatogaryObject.Data.Rows.Count);

    collectionCounts = new int[bookCatogaryObject.Data.Rows.Count];

    DataClassArray = new DataClass[bookCatogaryObject.Data.Rows.Count];

    for (int i = 0; i <= bookCatogaryObject.Data.Rows.Count; i++)
    {
        Debug.Log("==========>######" + bookCatogaryObject.Data.Rows[i].String.Count);
        ***collectionCounts[i] = bookCatogaryObject.Data.Rows[i].String.Count;***

        ***DataClassArray[i].collectionData = new int[bookCatogaryObject.Data.Rows[i].String.Count];***

        for (int m = 0; m < bookCatogaryObject.Data.Rows[i].String.Count; m++)
        {
            Debug.Log(bookCatogaryObject.Data.Rows[i].String[m].CollectionTitle);
        }
    }
}

Here is the method where I’m trying to initialize the arrays, but when I run the code I get an error "NullReferenceException: Object reference not set to an instance of an object" at Line : " DataClassArray[i].collectionData = new int[bookCatogaryObject.Data.Rows[i].String.Count];". Im not able to figure out where exactly the issue is.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Add

DataClassArray[i] = new DataClass();

right before

DataClassArray[i].collectionData = new int[bookCatogaryObject.Data.Rows[i].String.Count];

When you create an array, each element is null, so you need to create an element before trying to access its members.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading