C sharp - Unary Operator Overloading in C#

In C#, unary operator overloading allows you to define custom behavior for operators that operate on a single operand (like +, -, !, ++, --, etc.) for your user-defined types

Unary Operators You Can Overload

Operator Description
+ Unary plus
- Unary minus
! Logical negation
~ Bitwise complement
++ Increment
-- Decrement
true / false Logical evaluation (advanced)

Syntax for Overloading a Unary Operator

public static ReturnType operator (Type operand)

Example: Overloading Unary - and ++

public class Counter
{
    public int Value { get; set; }

    public Counter(int value)
    {
        Value = value;
    }

    // Overload unary -
    public static Counter operator -(Counter c)
    {
        return new Counter(-c.Value);
    }

    // Overload ++
    public static Counter operator ++(Counter c)
    {
        c.Value++;
        return c;
    }

    public override string ToString()
    {
        return $"Counter: {Value}";
    }
}

Example usage

class Program
{
    static void Main()
    {
        Counter c1 = new Counter(5);
        Console.WriteLine(c1);       // Counter: 5

        Counter c2 = -c1;
        Console.WriteLine(c2);       // Counter: -5

        c1++;
        Console.WriteLine(c1);       // Counter: 6
    }
}

Notes

  • Unary operator overloads must be public static.

  • For ++ and --, the return type is typically the same as the operand's type.

  • You can overload true and false to control how an object is evaluated in conditions, but it’s rare and more complex.

 Summary

  • Unary operator overloading lets you define how -, ++, --, etc. behave for your objects.

  • Must be public static.

  • Typically returns a new object or modifies and returns the existing one.