We might want two instances of a person to be able to procreate.
Add the following method to the Person
class:
// method to "multiply" public Person Procreate(Person partner) { var baby = new Person { Name = $"Baby of {this.Name} and {partner.Name}" }; this.Children.Add(baby); partner.Children.Add(baby); return baby; }
At the top of the Program.cs
file, type the following code to import the namespace for our class and statically import the Console
type:
using Packt.CS7; using static System.Console;
Now, we can get two people to make a baby by adding the following to the Main
method of the Program.cs
file:
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."); WriteLine($"{harry.Name}'s first child is named "{harry.Children[0].Name}".");
Run the console application and view the output:
Mary has 1 children. Harry has 1 children. Harry's first child is named "Baby of Harry and Mary".
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 inside the Person
class:
// 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, but before writing the children, count to the console:
var baby1 = harry.Procreate(mary);
var baby2 = harry * mary;
WriteLine($"{mary.Name} has {mary.Children.Count} children.");
Run the application and view the output:
Mary has 2 children. Harry has 2 children. Harry's first child is named "Baby of Harry and Mary".
Good Practice
Since it may not be obvious to a programmer who is using your class that instances of the class can use an operator, it's best to have both a method and an operator that perform the same function. For example, the string
type has both a Concat
method and can use the +
operator to concatenate two strings together.
3.146.34.146