Pages

Monday, 15 June 2015

Operator

Operators

Operator can be used for both predifined and userdefined type, as long as it's possible to overload. You can see list operator here.

Here's some restriction of operator overloading:
  • Operator overloading is available only for classes and structs.
  • You can overload an operator x for use with your class or struct by declaring a method named operator x that implements the behavior (for example, operator +, operator - , and so on).
    • The overload methods for unary operators take a single parameter of the class or struct type.
    • The overload methods for binary operators take two parameters, at least one of which must be of the class or struct type.
  • The declaration of an operator overload method requires the following:
    • The declaration must use both the static and public modifiers.
    • The operator must be a member of the class or struct for which it is an operator.
Use following syntax to overload the operator
public static [Userdefined Type : as return type] operator [operator symbol]([Operand List])
{
 [Operation's statements]
}

See following example:
class myClass
{
 public int intField;
 public float floatField;

 public static myClass operator +(myClass op1, myClass op2)  //overloading additive +
 {
  op1.intField += op2.intField;
  op1.floatField += op2.floatField;
  return op1;
 }

 public static myClass operator +(myClass op1)       //overloading unary +
 {
  op1.intField = + op1.intField;
  op1.floatField = + op1.floatField;
  return op1;
 }

 public static myClass operator ++(myClass op1)      //overloading increment ++
 {
  ++op1.intField;
  ++op1.floatField;
  return op1;
 }
}

class Program
{
 static void Main(string[] args)
 {
  myClass object1 = new myClass() { intField = -7, floatField = 4.5F };
  myClass object2 = new myClass() { intField = 10, floatField = 7.8F };

  Console.WriteLine("object1 intField = " + object1.intField + " floatField = " + object1.floatField);
  Console.WriteLine("object2 intField = " + object2.intField + " floatField = " + object2.floatField);
  
  //calling unary +
  object1 = +object1;
  Console.WriteLine("object1 intField = " + object1.intField + " floatField = " + object1.floatField);
  
  //calling additive +
  object1 += object2;
  Console.WriteLine("object1 intField = " + object1.intField + " floatField = " + object1.floatField);
  
  //calling increment ++
  ++object1;
  Console.WriteLine("object1 intField = " + object1.intField + " floatField = " + object1.floatField);
 }
}

After compiling and running the code you will find following in the display:
object1 intField = -7 floatField = 4,5
object2 intField = 10 floatField = 7,8
object1 intField = -7 floatField = 4,5
object1 intField = 3 floatField = 12,3
object1 intField = 4 floatField = 13,3

0 comments:

Post a Comment