0

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"));
}

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

0

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");
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.