Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to overload postfix and prefix operator in c# [duplicate]

Tags:

c#

How do we implement the overload 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 might be an unnecessary operator overload, but its known that ++ operator can be overloaded. How do we achieve the different behaviour here ( i++, ++i)

like image 784
singsuyash Avatar asked Nov 05 '22 00:11

singsuyash


1 Answers

From what I've seen, overloading the unary operator ++ in C# overloads both the 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

like image 122
sohil Avatar answered Nov 12 '22 14:11

sohil