Operator Functions - CSharp Custom Type

CSharp examples for Custom Type:Operator Overloading

Introduction

An operator is overloaded by declaring an operator function.

Overloading an operator automatically overloads the corresponding compound assignment operator.

In the following example, we define a struct called MyValue representing a musical note and then overload the + operator:

Demo Code

struct MyValue
{
    int value;
    public MyValue(int semitonesFromA)
    {//w  w  w .  jav  a2  s  .c o m
        value = semitonesFromA;
    }
    public static MyValue operator +(MyValue x, int semitones)
    {
        return new MyValue(x.value + semitones);
    }
}
class Test
{
    static void Main()
    {
        MyValue B = new MyValue(2);
        MyValue a = B + 2;
        a += 2;
    }
}

Related Tutorials