#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.

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: