2.5 Overloading Operators

 <  Day Day Up  >  

Rather than use methods , you want clients using your class to manipulate your object using built-in C# operators.


Technique

Create a new public static method in your class with any return type. For the method name , use the operator keyword followed by the actual operator you want to overload. Finally, for a unary operator, create a single parameter of a specified type; for a binary operator, create two parameters of a specified type; and for a conversion operator, create a parameter of the type you want to convert from. Listing 2.4 shows how to overload the unary operator ++ , which causes an internal member variable to be incremented.

Listing 2.4 Overloading the ++ Operator to Increment an Internal Member Variable
 public class Television {     /// <summary>     /// current channel tv is set to     /// </summary>     private static int channel = 2;     private const int maxChannels = 200;     /// <summary>     /// changes the channel to a specified channel     /// </summary>     public bool ChangeChannel(int newChannel)     {         if( newChannel > maxChannels )             return false;         channel = newChannel;         return true;     }     public static Television operator ++( Television tv )     {         tv.ChangeChannel(++channel);         return tv;     }     public int GetChannel()     {         return channel;     }     static void Main(string[] args)     {         Television tv = new Television();         for( int i = 0; i < 20; ++i )         {             tv++;             Console.WriteLine( "{0}", tv.GetChannel());         }     } } 

Comments

Operator overloading allows users of your code to interact with the objects it creates by using a syntax that's familiar to them and undoubtedly more natural. However, one of the main design tenants with operator overloading is to ensure that the operator you are overloading makes sense and feels natural. In Listing 2.4, choosing to overload the ++ operator for the Television class is probably not a good idea. Ambiguity is the most common design error when overloading an operator. Although the intention was to change the channel when using the increment operator, it's not clear because you are incrementing the actual television object and not a channel object for instance. However, because the listing was simply for illustration purposes, this sort of design is fine.

There are three available types of operators that you can overload, each with its own set of actual defined operators. Unary operators are designed to work with a single operand. They include the negation operator ( - ), the increment and decrement operators ( ++ and -- ), and the logical negation operator ( ! ). Because there is only a single operand, the overload function only needs one parameter, whose type is the same as the operand the operator is applied to. In the operator overload function in Listing 2.4, you see that a Television object is passed as the parameter, which then allows someone to apply the increment operator to any Television object. Determining the method signature for unary operators is simple because all unary operators must contain the same type for its return value and single parameter. Furthermore, this type is the same as the containing class, which is overloading the operator.

Binary operators such as operators for addition and subtraction and relational and logical operators, to name a few, must contain two parameters in their method signature. Furthermore, at least one of these parameters must be the same type as that of the containing class. The return value, on the other hand, can be any type. When using binary operators, you must ensure that your object still obeys commutative laws. If you add your object to some number, you should get the same result if you reverse the order of the operands and instead add some number to your object. Using the Television class of Listing 2.4, you would need to create two methods for the addition operator. The signatures for these would be the following:

 
 static Television operator + ( Television operand1, int operand2 ); static Television operator + (int operand1, Television operand2 ); 

The last operator type is the conversion operator. You use it when converting a value from one type to another, and it consists of the implicit and explicit conversion operators. An implicit conversion means that the conversion occurs transparently from the programmer performing the conversion. An explicit conversion requires a cast of the original type using the resultant type to convert to. Both of these operators require that the same type as the containing class be either the type you are converting from or the type you are converting to. The format is a little different than that of previous operator overloading methods. Instead of specifying a result type following the static keyword, you specify either implicit or explicit , depending on which type conversion you want to perform. Also, instead of using a predefined operator following the operator keyword, you use the type name of the type you want to convert to. To implicitly convert an integer to a new Television type from Listing 2.4, the implicit conversion function would be

 
 public static implicit operator Television( int from ) {     Television tv = new Television();     tv.ChangeChannel( from );     return tv; } 

By doing this conversion, you are enabling someone to use the following syntax on a Television object:

 
 static void Main(string[] args) {     Television tv = 5; } 
 <  Day Day Up  >  


Microsoft Visual C# .Net 2003
Microsoft Visual C *. NET 2003 development skills Daquan
ISBN: 7508427505
EAN: 2147483647
Year: 2003
Pages: 440

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net