juanito
juanito

Reputation: 23

Can't add objects to an array after initializing the array

I'm trying to initialize an array of objects with predetermined values but I get "Object reference not set to an instance of an object".
I don't understand the cause of the problem since I'm initializing properly and then I'm adding values to the array.
The main is:

Sorteo P=new Sorteo();
P.Predetermined();

Class Sorteo:

// Atribute
private ClassA[] A;
int count=0;

// Methods
public Sorteo()
{
    A=new ClassA[2];
}
public void Add(ClassA a)
{
    A[count]=a;
    count++;
}
public void PredeterminedValues()
{
    A[0].Add(new ClassB("SomeString1"));
    A[1].Add(new ClassB("SomeString2"));
}

Upvotes: 0

Views: 143

Answers (2)

André B
André B

Reputation: 1709

You're dealing with an array of reference types, not a value type.

In the following line:

    A = new ClassA[2]; 
    //[0] -> null
    //[1] -> null

you have indeed initialized an array which holds reference objects of type ClassA.

In this case it actually holds two variables of type ClassA, but each of them is going to be set to null (since you have't initialized those), and therefore when you try to reference them the exception Object reference not set to an instance of an object is going to be thrown.

Solution?

Add this after initializing your array

A[0] = new ClassA(); // not null anymore
A[1] = new ClassA(); // not null anymore

Upvotes: 2

Lift
Lift

Reputation: 546

I'm struggling to understand your question but is this what you were trying to do?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace YourNameSpace
{
    public class Program
    {
        public static void Main(string[] args)
        {
            ClassA Item = new ClassA();
            Item.PredeterminedValues();

            foreach(string s in Item.StringArray)
            {
                Console.WriteLine(s);
            }
        }
    }

    public class ClassA
    {
        public int Counter {get;private set;}
        public string[] StringArray{get;private set;}

        public ClassA()
        {
            StringArray = new string[2];
        }

        public void Add(int Value)
        {
            Counter += Value;   
        }

        public void PredeterminedValues()
        {
            StringArray[0] = ("SomeString1");
            StringArray[1] = ("SomeString2");
        }
    }
}

Upvotes: 0

Related Questions