Most sources say that overloading ++ and - operators in C # leads to overloading both the postfix and the prefix immediately. But it looks like their behavior is still different.
class Counter
{
public Counter(int v = 0)
{
this.v = v;
}
public Counter(Counter c)
{
v = c.v;
}
public int GetValue() { return v; }
public static Counter operator ++(Counter c)
{
c.v++;
return new Counter(c);
}
private int v;
}
class Program
{
public static void Main()
{
Counter c1 = new Counter(1);
Counter c2 = c1++;
Counter c3 = ++c1;
c3++;
System.Console.WriteLine("c1 = {0}", c1.GetValue());
System.Console.WriteLine("c2 = {0}", c2.GetValue());
System.Console.WriteLine("c3 = {0}", c3.GetValue());
}
}
Miraculously, although the overloaded one operator ++returns a copy of the source class, in this example c1they c3become references to the same object, but c2point to another ( c1=4, c2=2, c3=4here). Change Counter c3 = ++c1;to Counter c3 = c1++;displays c1=3, c2=2, c3=4.
So, what is the exact difference between increment and decrement prefix and prefix, and how does it affect overload? Are these operators the same for classes and primitive types?
source
share