Operator Overloading in C# - C# Tutorials

Latest

For Video tutorials Visit my Channel https://www.youtube.com/channel/UCVWpZVbMqLHuQBigIfc9I8Q

Tuesday, 14 February 2017

Operator Overloading in C#

using System;
class Widget
{
    public int _value;
    public static Widget operator +(Widget a, Widget b)
    {
        // Add two Widgets together.
        // ... Add the two int values and return a new Widget.
        Widget widget = new Widget();
        widget._value = a._value + b._value;
        return widget;
    }
    public static Widget operator ++(Widget w)
    {
        // Increment this widget.
        w._value++;
        return w;
    }
}
class Program
{
    static void Main()
    {
        // Increment widget twice.
        Widget w = new Widget();
        w++;
        Console.WriteLine(w._value);
        w++;
        Console.WriteLine(w._value);
        // Create another widget.
        Widget g = new Widget();
        g++;
        Console.WriteLine(g._value);
        // Add two widgets.
        Widget t = w + g;
        Console.WriteLine(t._value);
        Console.ReadKey();
    }

}

No comments:

Post a Comment