0

A very, very simple C# question.

I want to create a normal little array of a type that is another class.

bits of the code:

class Program
{
    static void Main(string[] args)
    {
        classA[] test;
        test = new classA[2];
        Console.Write(test[0].getName());


class classA
{
    string name;
    public classA()
    {
        this.name = "zup";
    }
    public string getName()
    {
        return this.name;
    }

Why wont it let me ?

1
  • You don't fill the array. Normally test[0].getName() should lead to a NullReferenceException. Commented Jun 2, 2013 at 14:10

3 Answers 3

2

When you create an array of a reference type like that, the array is initialised with nulls - no actual objects are constructed (other than the array itself).

Therefore you need to explicitly create each element of your array.

For your example, you will need to do this:

classA[] test;
test = new classA[2];
test[0] = new classA();
test[1] = new classA();

Note that if you were using a value type such as a struct or a primitive type (int, double, char etc) this would not be necessary.

You often write a loop to initialise an array, so again for your code sample:

classA[] test;
test = new classA[2];

for (int i = 0; i < test.Count; ++i)
    test[i] = new classA();
Sign up to request clarification or add additional context in comments.

Comments

2

You create an array of type ClassA, but don't initalize the elements, so the elements in the array are all null. To make a simple test array, with content, use an array initializer instead:

var test = new ClassA[] { new ClassA(), new ClassA() };

Comments

1

you can do it as below

test = new classA[2].Select(c=>new classA()).ToArray();

after you call new classA[2] you have null items in the array. above code will add new ClassA object to each array item. Now you can call Console.Write(test[0].getName()); without exception

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.