#1,099 – Overloading the Increment Operator

You can overload the increment (++) operator in a class, providing custom increment functionality for an object.

The example below shows an overloaded increment operator defined in a Dog class.  The effect is to add 1 to the age of the dog.  We are careful to return a reference to the object that was passed in so that no other data in the instance changes.

    public class Dog 
    {
        // Increment a Dog
        public static Dog operator ++(Dog d)
        {
            d.Age++;
            return d;
        }

        public string Name { get; set; }
        public int Age { get; set; }
        public string Nickname { get; set; }

        public Dog(string name, int age)
        {
            Name = name;
            Age = age;
            Nickname = "?";
        }

        public override string ToString()
        {
            return string.Format("{0}, Age {1}, Nickname [{2}]", Name, Age, Nickname);
        }
    }

We can use the operator as follows:

            Dog kirby = new Dog("Kirby", 10);
            kirby.Nickname = "Ball Chaser";
            Console.WriteLine(kirby);

            kirby++;
            Console.WriteLine(kirby);

1099-001

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

One Response to #1,099 – Overloading the Increment Operator

  1. Pingback: Dew Drop – May 19, 2014 (#1779) | Morning Dew

Leave a comment