Simplifying methods with operators
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". ...
Get C# 6 and .NET Core 1.0: Modern Cross-Platform Development now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.