Reputation: 2698
I want to put values inside my class array and a class inside a class. Below is my class:
public class Person
{
public string typeOfPerson { get; set; }
public Persondetails personDetails { get; set; }
public Name[] names { get; set; }
}
public class Persondetails
{
public string dateOfBirth { get; set; }
}
public class Name
{
public string firstName { get; set; }
public string middleNames { get; set; }
public string surName { get; set; }
}
I want to assign value to dateofBirth and names. I already initiated the person class:
Person person = new Person();
Persondetails pd = new Persondetails();
pd.dateOfBirth = "12/03/2020";
How can I add date of birth to Person class. I also want to assign values to firstName, middleNames and surnames like so:
"names": [
{
"firstName": "ROGER",
"middleNames": "D",
"surName": "STANLEY"
}
]
Any help will be greatly apprecaited.
Upvotes: 0
Views: 58
Reputation: 2804
You can't change the size of an array, so unless you initialized the array before and know exactly which one you want to change, you should use a List. Then you can do the following:
public class Person
{
public string typeOfPerson { get; set; }
public Persondetails personDetails { get; set; }
public List<Name> names { get; set; } = new List<Name>();
}
public void YourMethod()
{
Person person = new Person();
Persondetails pd = new Persondetails();
pd.dateOfBirth = "12/03/2020";
person.names.Add(new Name { firstName = "ROGER", middleName = "D", surName = "STANLEY" });
}
Upvotes: 1