C# operator overloading

Posted on 5:41pm 1/04/2008 by Bruno Silva in .NET, Programming

I’ve found out about a nice C# feature that I didn’t know about. Operator overloading. It allows you to define the operators like +,-,/*,+=,-=,!=,etc. for the classes you develop. How? Just add an static method named operator-<operator> where <operator> can be an operator like +. The first parameter must be of your class type (in this example MyType), the second one can be of any type. Inside the method body you implement the logic associated with your overloaded operator, returning an instance of your class.

public static MyType operator+(MyType o1,MyType o2){
     return new MyType(o1.Property1 + o2.Property1);
}
public static MyType operator+(MyType o,int i){     
     return new MyType(o.Property1 + i);

}

The code above allows you to do something like this:

MyType o1 = new MyType(10);
MyType o2 = new MyType(5);

MyType rs = o1 + o2;

Another nice feature is related with cast operations. You can allow something like (int)o1 (where o1 is an instance of MyType) by adding another static method to your MyType class. explicit/implicit keywords define if you must add (type) before your instance to trigger the cast. Implicit does an implicit cast when it is needed. With explicit you must and the (type) to cast.

public static explicit operator int (MyType from){
     return from.Property1;
}

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

© Bruno Silva | Powered by Wordpress