C# let’s you overload the behaviour of some unary operator such as: unary plus, minus, prefix increment, decrement, true keyword, false keyword and more.
Ok, now let’s make a small example on how to overload the unary plus. For this, you need to define a method (in the class that you want to implement the overload) containing a few things: the return type, the operator keywords (in this case +), the parameter that usually is the object or structure where the method is being defined.
Let’s make now a small example:
-First we create a small class and define the overload plus:
public class MyClass
{
public double value;
public static MyClass operator +(MyClass Mc)
{
MyClass myC = new MyClass();
if (Mc.value <0)
myC.value = -Mc.value;
else
myC.value = Mc.value;
return myC;
}
}
-
static void
{
MyClass MyCs = new MyClass();
MyClass MyCsP = new MyClass();
//Both negative and positive values to see effect
MyCs.value = -10.80;
MyCsP.value = 300;
Console.WriteLine("Before: " + MyCs.value);
Console.WriteLine("\t" + MyCsP.value);
//Using the + operator triggers the method
MyCs = +MyCs;
MyCsP = +MyCsP;
Console.WriteLine("After: " + MyCs.value);
Console.WriteLine("\t" + MyCsP.value);
Console.Read();
}
No comments:
Post a Comment