We might want two instances of a person to be able to procreate. We could do this with the following method:
// method to "multiply" public Person Procreate(Person partner) { var baby = new Person("Baby"); Children.Add(baby); partner.Children.Add(baby); return baby; }
Now, we can get two people to make a baby:
var harry = new Person { Name = "Harry" }; var mary = new Person { Name = "Mary" }; var baby1 = harry.Procreate(mary); WriteLine($"{mary.Name} has {mary.Children.Count} children."); WriteLine($"{harry.Name} has {harry.Children.Count} children.");
Run the application and view the output:
Mary has 1 children. Harry has 1 children.
An alternative would be to define an operator to allow two people to "multiply". To allow this, we need to define a static operator for the *
symbol:
// operator to "multiply" public static Person operator *(Person p1, Person p2) { return p1.Procreate(p2); }
Add the following code at the end of the Main
method...