Adding a New Operator – Scout Adding a New Operator – Scout

Adding a New Operator

In C#, comparing two objects to one another requires there to be a comparator defined. In the case of GuardedVariables, we must specifically define these comparators.

For instance, take GuardedDecimal as an example. We specifically define how we want the == operator to determine equality using the following code snipped from GuardedDecimal.cs. In this instance, two instances of GuardedDecimal are considered equal if their decrypted values are the same.

C# – GuardedDecimal.cs
/// <summary>
/// Overload the == operator.
/// </summary>
/// <param name="v1"></param>
/// <param name="v2"></param>
/// <returns></returns>
public static bool operator ==(GuardedDecimal v1, GuardedDecimal v2) => v1.GetDecryptedValue() == v2.GetDecryptedValue();

Other operators such as +, -, / can be defined using this method.

Furthermore, if we define the == operator, we should also define the != operator and .Equals and .CompareTo (Used in >, >=, < and <=).

C#
/// <summary>
/// Overload the != operator.
/// </summary>
/// <param name="v1"></param>
/// <param name="v2"></param>
/// <returns></returns>
public static bool operator !=(GuardedDecimal v1, GuardedDecimal v2) => !(v1 == v2);
/// <summary>

/// Compare this decimal's decrypted value to another decimal.
/// </summary>
/// <param name="o"></param>
/// <returns></returns>
public override int CompareTo(decimal o) => GetDecryptedValue().CompareTo(o);

/// <summary>
/// Compare this decimal's decrypted value to another encrypted decimal's decrypted value.
/// </summary>
/// <param name="o"></param>
/// <returns></returns>
public override int CompareTo(_GuardedType<decimal> o) => GetDecryptedValue().CompareTo(o.GetDecryptedValue());

/// <summary>
/// Check equality between this decimal's decrypted value and another decimal.
/// </summary>
/// <param name="o"></param>
/// <returns></returns>
public override bool Equals(decimal o) => GetDecryptedValue() == o;

/// <summary>
/// Check equality between this decimal's decrypted value and another encrypted decimal's decrypted value.
/// </summary>
/// <param name="o"></param>
/// <returns></returns>
public override bool Equals(_GuardedType<decimal> o) => GetDecryptedValue() == o.GetDecryptedValue();

/// <summary>
/// Check for equality when the type is unknown.
/// 
/// Currently, we only check primitive type comparisons and Guarded type comparisons.
/// 
/// This can be extended to check for equality across types. Such as bool being checked against '1' or '0'.
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public override bool Equals(object other) {
    if (other is decimal)
        return Equals((decimal)other);

    if (other is GuardedDecimal)
        return Equals((GuardedDecimal)other);

    return false;
}

Take these examples and apply the logic to create your own operators for GuardedVariables.

Powered by BetterDocs