Home > Back-end >  How to instantiate an array inside nested objects in C#
How to instantiate an array inside nested objects in C#

Time:02-03

I'm trying to assign a value to property of an object inside a complex object with nested types. One of the types is an Array. And that is where I am getting stuck. I have a complex object with many nested objects. One of the objects is an Array[]. I am trying to assign the request parameter accountNumber to the AccountNumber property of AccountKeyType. But I am stuck on initializing the AccountType array Object. Here is my class structure:

    public class Customer
{
    public AccountType[] Accounts { get; set; }
}

public partial class AccountType
{
    public AccountKeyType AccountKey { get; set; }
}

public class AccountKeyType
{
    public string AccountNumber { get; set; }
}

Here is where I am getting stuck:

                        Customer = new Customer
                    {
                        Accounts = new AccountType[0]
                        {
        //How do I access the nested object **AccountKeyType.AccountNumber** like this:
            //AccountKeyType.AccountNumber = request.AccountNumber
                        }
                    }

**Update: This is the fix:

                        Customer = new Customer
                    {

                        Accounts = new AccountType[]
                        {
                            new AccountType() { AccountKey = new AccountKeyType()
                                {
                                  AccountNumber=request.AccountNumber
                                }
                            }
                        }

                    }

CodePudding user response:

You need to instantiate an AccountType in your AccountType[]

Customer = new Customer
{
    Accounts = new AccountType[]
    {
        new AccountType() { AccountNumber = request.AccountNumber }
    }
}

Or if you want to instantiate multiple

Customer = new Customer
{
    Accounts = new AccountType[]
    {
        new AccountType() { AccountNumber = accountNumber1 },
        new AccountType() { AccountNumber = accountNumber2 }
    }
}
  •  Tags:  
  • Related