Using DynamicObject it’s possible to create a custom class and define its behavior when an instance is compared with something else. It’s done by overriding TryBinaryOperation.
However, when I try to compare it with null or any reference value the overridden method is never called.
public class Foo : DynamicObject
{
public override bool TryBinaryOperation(BinaryOperationBinder binder, object arg, out object result)
{
if (binder.Operation == ExpressionType.Equal)
{
result = true;
return true;
}
return base.TryBinaryOperation(binder, arg, out result);
}
}
static void Main(string[] args)
{
dynamic foo = new Foo();
Console.WriteLine(foo == 1); // True
Console.WriteLine(foo == new object()); // False
Console.WriteLine(foo == null); // False
}
Is there a way to intercept this call? I would assume DynamicObject is not the correct abstraction for this.
Yes you can via operator overloading. In fact, I use this trick to implement a dynamic expression builder in my DynamicLinq project. See an example here:
https://github.com/davidfowl/DynamicLinq/blob/master/DynamicLINQ/DynamicExpressionBuilder.cs#L88