How to overload postfix and prefix operator in C #

How to implement overloading for postfix and prefix operators in C #

void Main()
{
    MyClass myclass=new MyClass();
    myclass.x=5;
    Console.WriteLine((++myclass).x);
          Console.WriteLine((myclass++).x);
}

public class MyClass
{
    public int x;
    public static MyClass operator ++(MyClass m)
    {
        m.x=m.x+1;
        return m;
    }

}

this may be an unnecessary operator overload, but it is known that the ++ operator can be overloaded. How can we achieve different behavior here (i ++, ++ i)

+5
source share
2 answers

From what I saw, overloading the unary operator ++ in C # overloads both postfix and prefix versions of the operator.

Sources: http://devhawk.net/2003/07/09/operator-overloading-in-c/  http://www.programmingvideotutorials.com/csharp/csharp-operator-overloading

+2
source

The incremental increment overload accepts int parameters, and the prefix does not

like:

public static MyClass operator ++(MyClass m)
{
    m.x=m.x+1;
    return m;
}

public static MyClass operator ++(MyClass m, int i)
{
    m.x=m.x+1;
    return m;
}

but it seems the int value is useless lol

: http://msdn.microsoft.com/en-us/library/f6s9k9ta(v=vs.80).aspx

-1

All Articles