#397 – Defining an Operator

You can define an operator in a class, so that the operator can be used in expressions that include instances of the class.

For example, suppose you want to define the plus (+) operator so that it has some meaning when applied to instances of the Dog class.

            Dog k = new Dog("Kirby", 13);
            Dog j = new Dog("Jack", 15);

            Dog mutant = k + j;

To define an operator in your class, you define a new public static method that includes the operator keyword.

In the example below, we define the plus (+) operator for the Dog class, which allows “adding” two dogs.

        public static Dog operator +(Dog d1, Dog d2)
        {
            return new Dog(d1.Name + d2.Name, d1.Age + d2.Age);
        }

This method returns a new instance of a Dog, with the two names appended together and the dogs’ ages added.

Advertisement