Operator keyword - Operator Overloading

While studying for my MCPD, I stumbled upon the operator keyword. Operator overloading permits user-defined operator implementations to be specified for operations where one or both of the operands are of a user-defined class or struct type,

For instance, we can create a Cycle class that cycles between defined minimum and maximum values.

We start off by defining our user-defined type Cycle wich will be of type struct ( a value type ):

 

Cycle struct definition :

   1: public struct Cycle
   2: {
   3:  
   4: }

 

Cycle struct Characteristics :

   1: public struct Cycle
   2: {
   3:      int _val;
   4:      int _max ;
   5:      int _min;
   6:  
   7: }
Code Explanation :

We declare 3 variables:

_max and _min as boundaries variables.
_val as the current value.

 

Cycle Class Constructor :

   1: public struct Cycle
   2: {
   3:        int _val;
   4:        int _max ;
   5:        int _min;
   6:  
   7:        public Cycle(int minimum, int maximum)
   8:        {
   9:            _val = minimum;
  10:            _max = maximum;
  11:            _min = minimum;
  12:        }
  13:  
  14: }
Code Explanation :

The Constructor job is the initialize class variables. I initialize the current value _val to the minimum value provided as a start point of Cycling.

 

Cycle class Properties ( Exposed Characteristics ) :

   1: struct Cycle
   2: {
   3:        int _val;
   4:        int _max ;
   5:        int _min;
   6:  
   7:        public Cycle(int minimum, int maximum)
   8:        {
   9:            _val = minimum;
  10:            _max = maximum;
  11:            _min = minimum;
  12:        }
  13:  
  14:        public int Value
  15:        {
  16:            get { return _val; }
  17:            set
  18:            {
  19:                if (value > _max)
  20:                {
  21:                    _val = _min;
  22:                }
  23:                else if (value < _min)
  24:                {
  25:                    _val = _max;
  26:                }
  27:                else
  28:                {
  29:                    _val = value;
  30:                }
  31:            }
  32:        }
  33: }
Code Explanation :

The Cycle class exposes one propertey called Value, this property will be used in our example to display the different values while the cycle class is in action.

To initiate a cyclic behavior we are forced to reset the cycle everytime the value hits the max value so it is either _min, _max, or value ( current value in the cyclic phase)

 

Our beloved Operators :

   1: public struct Cycle
   2: {
   3:        int _val;
   4:        int _max ;
   5:        int _min;
   6:  
   7:        public Cycle(int minimum, int maximum)
   8:        {
   9:            _val = minimum;
  10:            _max = maximum;
  11:            _min = minimum;
  12:        }
  13:  
  14:        public int Value
  15:        {
  16:            get { return _val; }
  17:            set
  18:            {
  19:                if (value > _max)
  20:                {
  21:                    _val = _min;
  22:                }
  23:                else if (value < _min)
  24:                {
  25:                    _val = _max;
  26:                }
  27:                else
  28:                {
  29:                    _val = value;
  30:                }
  31:            }
  32:        }
  33:  
  34:        public override string ToString()
  35:        {
  36:            return Value.ToString();
  37:        }
  38:  
  39:        public int ToInteger()
  40:        {
  41:            return Value;
  42:        }
  43:  
  44:        public static Cycle operator +(Cycle arg1, int arg2)
  45:        {
  46:            arg1.Value += arg2;
  47:            return arg1;
  48:        }
  49:  
  50:        public static Cycle operator -(Cycle arg1, int arg2)
  51:        {
  52:            arg1.Value -= arg2;
  53:            return arg1;
  54:        }
  55: }
Code Explanation :

We overload the + and the - operators using the syntax provided above:

Our template is as follows : arg1.Value += arg2; this line of code defines the way this overloaded operator should be used. it just increment the Value property of Cycle object with an incremental arg2 value. The current object is returned arg1.

same for the - operator.

 

Our Cycle class in action :

   1: protected void Page_Load(object sender, EventArgs e)
   2: {
   3:            Cycle degrees = new Cycle(0, 360);
   4:            for(int i = 0; i < 6; i++)
   5:            {
   6:                degrees += 60;
   7:                Response.Write(degrees.Value + ", ");
   8:            }
   9:            
  10: }

 

Code Explanation :

We first instantiate a cycle class called degrees that represents the rotation angle in a circle. The _min and _max are defined in the constructor as 0 and 360.

We create a loop, to stimulate the rotation behavior and the magic starts with this line of code : degrees += 60;

here's the workflow : degrees += 60 invokes arg1.Value += arg2 ( arg1 represents degrees, Value is 0, arg2 is 60 ) invokes the Values property that assign 60 to _val wich is the return value of Value.

The Second iteration Value is 60 , Third Iteration 120 and so on. When Value hits max it resets to 0 making the rotation cyclic.

 

Complete Code ( Code behind ):

   1: using System;
   2: using System.Collections;
   3: using System.Configuration;
   4: using System.Data;
   5: using System.Linq;
   6: using System.Web;
   7: using System.Web.Security;
   8: using System.Web.UI;
   9: using System.Web.UI.HtmlControls;
  10: using System.Web.UI.WebControls;
  11: using System.Web.UI.WebControls.WebParts;
  12: using System.Xml.Linq;
  13:  
  14: namespace MCTS___Foundation
  15: {
  16:     public partial class _Default : System.Web.UI.Page
  17:     {
  18:         protected void Page_Load(object sender, EventArgs e)
  19:         {
  20:             Cycle degrees = new Cycle(0, 360);
  21:             for(int i = 0; i < 6; i++)
  22:             {
  23:                 degrees += 60;
  24:                 Response.Write(degrees.Value + ", ");
  25:             }
  26:             
  27:         }
  28:     }
  29:  
  30:     public struct Cycle
  31:     {
  32:         int _val;
  33:         int _max ;
  34:         int _min;
  35:  
  36:         public Cycle(int minimum, int maximum)
  37:         {
  38:             _val = minimum;
  39:             _max = maximum;
  40:             _min = minimum;
  41:         }
  42:  
  43:         public int Value
  44:         {
  45:             get { return _val; }
  46:             set
  47:             {
  48:                 if (value > _max)
  49:                 {
  50:                     _val = _min;
  51:                 }
  52:                 else if (value < _min)
  53:                 {
  54:                     _val = _max;
  55:                 }
  56:                 else
  57:                 {
  58:                     _val = value;
  59:                 }
  60:             }
  61:         }
  62:  
  63:         public override string ToString()
  64:         {
  65:             return Value.ToString();
  66:         }
  67:  
  68:         public int ToInteger()
  69:         {
  70:             return Value;
  71:         }
  72:  
  73:         public static Cycle operator +(Cycle arg1, int arg2)
  74:         {
  75:             arg1.Value += arg2;
  76:             return arg1;
  77:         }
  78:  
  79:         public static Cycle operator -(Cycle arg1, int arg2)
  80:         {
  81:             arg1.Value -= arg2;
  82:             return arg1;
  83:         }
  84:     }
  85: }

 

Enjoy it!

Published Monday, January 28, 2008 10:28 PM by Joseph Ghassan
Filed under:

Comments

# re: Operator keyword - Operator Overloading

Monday, January 28, 2008 11:23 PM by electroslave

Hi Joseph,

I think you should check the code and be a bit more cautious before posting something, since the arithmetic operation on the cycle type should through an exception if it's over its max allowed value or under its min allowed value, and also maybe choose another example that has less things into it, for example for a value type of this sort the min and max should probably be at the type level instead of at the instance level, I know the point you are trying to make, but it is a bit confussing.

# re: Operator keyword - Operator Overloading

Tuesday, January 29, 2008 12:53 AM by Joseph Ghassan

Hi,

If you check the Value Property, I have already included a constraint everytime I set it., if the entered value is greater than max I reset the value to minimum and if its less than minimum I reset it to maximum.

It is just a simple example where a struct type is used, you can always use built-in types to create a more simpler example.

hope this clarified the ambiguity.

# re: Operator keyword - Operator Overloading

Wednesday, April 02, 2008 10:05 AM by Brian Mackey

This appears to be the same example they use in the 2.0 .NET Application foundation exam 70-536 study guide published by Microsoft.  Only, your explanation is far more thorough and I actually understand the operator keyword now.  

I nearly screamed Eureka! its an overload! when I read:

"We overload the + and the - operators using the syntax provided above: "

Thank you for clarifying this.  

# re: Operator keyword - Operator Overloading

Tuesday, August 26, 2008 8:12 AM by shane

electroslave dnt always try to find mistakes. this is a good blog. as Brian Mackey said this is the same example used in the .0 .NET Application foundation exam 70-536 study guide published by Microsoft.so go and challange them also. idea of this example is just to explain operators nothing else. Very good article.

Leave a Comment

(required) 
(required) 
(optional)
(required)