CSharp examples for Custom Type:Operator Overloading
Implement multiply operator
using static System.Console; using System;/*w ww .j av a 2s.co m*/ using System.Collections.Generic; using System.Text.RegularExpressions; class Program { static void Main(string[] args) { var harry = new Person { Name = "Harry" }; var mary = new Person { Name = "Mary" }; var jill = new Person { Name = "Jill" }; var baby1 = mary.ProcreateWith(harry); var baby2 = Person.Procreate(harry, jill); var baby3 = harry * mary; WriteLine($"{mary.Name} has {mary.Children.Count} children."); WriteLine($"{harry.Name} has {harry.Children.Count} children."); WriteLine($"{jill.Name} has {jill.Children.Count} children."); WriteLine($"{mary.Name}'s first child is named \"{mary.Children[0].Name}\"."); } } public class Person : IComparable<Person> { public string Name; public DateTime DateOfBirth; public List<Person> Children = new List<Person>(); public int CompareTo(Person other) { return Name.CompareTo(other.Name); } public Person ProcreateWith(Person partner) { return Procreate(this, partner); } // methods to "multiply" public static Person Procreate(Person p1, Person p2) { var baby = new Person { Name = $"Baby of {p1.Name} and {p2.Name}" }; p1.Children.Add(baby); p2.Children.Add(baby); return baby; } // operator to "multiply" public static Person operator *(Person p1, Person p2) { return Procreate(p1, p2); } }