DEV Community

Jefry Pozo
Jefry Pozo

Posted on • Updated on

Overloading unary operators in C#

This is the second entry in a series of posts about overloading operators in C#.

Previous entries:
-Introduction to operator overloading in C#

This time we're gonna see how to overload unary operators and some use cases.
Remember that in C# the unary operators are:

  • Addition (+)
  • Subtraction (-)
  • Logical negation (!)
  • Increment and decrement (++ and --)
  • Bitwise complement (~)
  • true and false

Basics of operator overloading

The C# language has a simple structure for the overload of operators, basically you define a static method on a type whose return type and parameters are the type itself. For example:

 public static <TypeName> operator <OperatorSymbol>(<Type>Name> typeName)
Enter fullscreen mode Exit fullscreen mode

where TypeName is the enclosing type, and OperatorSymbol is the operator to overload (+, -, and so on). You will understand it better when we get to the concrete examples.

For giving concrete examples and an easier comprehension, I'll be using a Temperature class on which we will overload the operators and apply our custom logic.

namespace UnaryOperators
{
    public enum TemperatureType
    {
        Celsius = 1,
        Farentheit,
        Kelvin
    }

    public class Temperature
    {
        public double Value { get; set; }
        public TemperatureType Type { get; set; }

        public Temperature(double value = 0, TemperatureType type = TemperatureType.Celsius)
        {
            Value = value;
            Type = type;
        }
  }
Enter fullscreen mode Exit fullscreen mode

We'll see how to use the operators on the Temperature object but modifying its underlying Value property.

The addition (+) operator

The addition operator by default just returns the current value of a numeric type in its unary form. We will change this behavior so it returns the absolute value of the temperature if it's lesser than 0 and return the current temperature value otherwise.

public static Temperature operator + (Temperature tempA)
{
   if (tempA.Value < 0) tempA.Value = System.Math.Abs(tempA.Value);
   return tempA;
}
Enter fullscreen mode Exit fullscreen mode

As you can see, the method receives a Temperature object and returns a Temperature object which, should be the rule since you will apply the operator on a Temperature object. When we get to the binary operators we'll see how to apply operands between our custom type and any other type.

The subtraction (-) operator

The subtraction operator by default returns the negative value of a numeric type. We will override this behavior so we can modify the underlying value by applying the operator to the Temperature object:

public static Temperature operator - (Temperature temp)
{
    temp.Value = - temp.Value;
    return temp;
}
Enter fullscreen mode Exit fullscreen mode

The increment (++) and decrement (--) operators

These are very straightforward, we will modify their behavior so they increment or decrement the temperature by 10 units.

public static Temperature operator ++(Temperature temp)
{
    temp.Value += 10;
    return temp;
}

public static Temperature operator --(Temperature temp)
{
    temp.Value -= 10;
    return temp;
}
Enter fullscreen mode Exit fullscreen mode

True and False operators

I don't really see a need to overload these operators, since you can use boolean flags instead. But one particular and very specific use these operators have is when you need to overload the OR (|) and AND (&) operators, since you need to implement the True and False for them to work.
Also, True and False work in pairs so if you overload one you must overload the other.

public static bool operator true (Temperature temp)
{
    if (temp.Type == TemperatureType.Celsius) return temp.Value < 40;
    if (temp.Type == TemperatureType.Farentheit) return temp.Value < 104;
    return temp.Value < 313.5;
}

public static bool operator false (Temperature temp)
{
    if (temp.Type == TemperatureType.Celsius) return temp.Value >= 40;
    if (temp.Type == TemperatureType.Farentheit) return temp.Value >= 104;
    return temp.Value >= 313.5;
}
Enter fullscreen mode Exit fullscreen mode

Say you'd like to check if a Temperature is at a high level and can cause dehydration .As you see in the code, I set the 40 grades celsius temperature as the threshold, so in practice you could use it like this:

var temperature = new Temperature(41, TemperatureType.Celsius);
if (temperature)
    Console.WriteLine($"Outside temp is {temperature.Value}. Looks like a sunny day");            
else
    Console.WriteLine($"Outside temp is {temperature.Value}. It's dangerous to be outside with this heat");

// Prints Outside temp is 41. It's dangerous to be outside with this heat
Console.ReadLine();
Enter fullscreen mode Exit fullscreen mode

Logical negation (!) and bitwise (~) operators

I couldn't find concrete use cases for these operators, but i'll explain the bitwise operator since the logical negation is very basic.

The bitwise operator works on numeric types by changing the zeros and ones that compose the number to their opposite value. Let's see an example:
If you have the decimal 78, in binary it would be 1001110.
When you apply the bitwise operation, all 1's are converted to 0's and viceversa; thus our binary number would be 0110001 which corresponds to the decimal 49.

Conclusion

This entry covered the basics of the operator overloading in C#, and how they can be used to change the behavior of some operations on our custom types. On the next post I'll be covering binary operators, which are a more interesting and useful aspect of the C# language.

Oldest comments (0)