How do I initialise a class within a class

51 Views Asked by At

In C# I have a class like this:

public class BClass
{
    public int Ndx { get; set; }
    public string Title { get; set; }
}

This is then used within this class

public class AClass
{
    public int Ndx { get; set; }
    public string Author { get; set; }
    public BClass[] Titles { get; set; }
}

Now when I populate author I do not know how many titles they have until run time so the number of instances of AClass.Titles there will be, so my question is how do I initialise this every time, please?

Thanks in advance

1

There are 1 best solutions below

0
Ineffable21 On BEST ANSWER

Instead of an array you can use a collection type like List<BClass>. This way, you can dynamically add BClass instances at runtime without worrying about the initial size of the array. This is how to do it:

using System.Collections.Generic;

public class ClassName
{
    public int titleNum { get; set; }
    public string author { get; set; }
    public List<BClass> Titles { get; set; }

    public ClassName()
    {
        Titles = new List<BClass>();
    }
}

Here is how to add items to the collection:

ClassName a = new ClassName();
a.titleNum = 1;
a.author = "Author Name";

a.Titles.Add(new BClass { titleNum = 1, Title = "Title 1" });
a.Titles.Add(new BClass { titleNum = 2, Title = "Title 2" });