#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)
            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";




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 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 )

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: