Initializing Array from a new class

Asked

Viewed 57 times

3

Considering two classes in C#:

public class aClass
{
    public string afield;
}

public class bClass
{
    public aClass[] bfield;
}

I plan to start the variable as

bClass cVar = new bClass();
cVar.bfield[0].afield = "text";

but is generating the following error during debug.

System.Nullreferenceexception: 'Object Reference not set to an instance of an Object.'

cVar.bfield was null.

How I start the variable to avoid this error?

  • 2

    Our language is the Português, translate your question.

  • Translate your question so I can signal you as a duplicate of O que é NullReferenceException. Responding: You need to initialize the field bfield or in the field declaration itself or in the constructor. Thus: bfield = new [] { new aClass() { afield = "conteúdo" } }

2 answers

5


Apparently your problem is that you did not initialize the "Array", to solve you could initialize it before assigning some value:

bClass cVar = new bClass();

cVar.bfield = new bfield[] {
    new aClass {
        afield = "text";
    };
};

Or

bClass cVar = new bClass();

cVar.bfield = new aClass[1];
cVar.bfield[0].afield = "text";

But for sure this would not be the best way to do what you want, an array does not provide all the flexibility you probably search for, maybe it is better you opt for a list, could do so:

public class aClass
{
    public string afield;
}

public class bClass
{
    public List<aClass> bfield = new List<aClass>();
}

bClass cVar = new bClass();

cVar.bfield.Add(new aClass {
    afield = "text"
});

0

I think the easiest implementation is to create an inline started property

public class bClass
{
    public aClass[] bfield => new aClass[10];
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.