Initializing Array of a new class

3

Considering two classes in C #:

public class aClass
{
    public string afield;
}

public class bClass
{
    public aClass[] bfield;
}

I want to start the variable as

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

but is generating the following error during the debug.

  

System.NullReferenceException: 'Object reference not set to an instance of an object.'

     

cVar.bfield was null.

How do I start the variable to avoid this error?

    
asked by anonymous 05.04.2018 / 21:40

2 answers

5

Apparently your problem is that you did not initialize the "Array", so you could initialize it before assigning any 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 this certainly would not be the best way to do what you want, an array does not provide all the flexibility you're likely to seek, you might want to opt for a list, you could do this:

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"
});
    
05.04.2018 / 22:02
0

I think the easiest implementation is to create an inline property

public class bClass
{
    public aClass[] bfield => new aClass[10];
}
    
05.04.2018 / 23:19