Final update: See this new question that narrows the problem down to generic structs.
I have some code that is building an Expression<Func<..>>
that compares a value type to the nullable of the same value type. In the line that defines the expression, I'm getting the following InvalidOperationException
:
The operands for operator 'Equal' do not match the parameters of method 'op_Equality'.
Any explanation for this?
Note: None of the overriden methods are ever called, the exception is thrown when the expression is being built by .NET
Here's the full code to reproduce the exception:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
namespace ConsoleApplication1
{
struct MyStruct<T> : IEquatable<MyStruct<T>>
where T : struct
{
private readonly T _value;
public MyStruct(T val) { this._value = val; }
public override bool Equals(object obj)
{
return false;
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public static bool operator ==(MyStruct<T> a, MyStruct<T> b)
{
return false;
}
public static bool operator !=(MyStruct<T> a, MyStruct<T> b)
{
return false;
}
public bool Equals(MyStruct<T> other)
{
return false;
}
}
class Program
{
static void Main(string[] args)
{
Expression<Func<MyStruct<int>, Nullable<MyStruct<int>>, bool>> expr =
(value, nullableValue) => value == nullableValue;
Console.ReadLine();
}
}
}
Update: Greatly simplified the code that reproduces the exception
Also: Note that using a Func instead of an expression does not cause this exception:
Func<MyStruct<int>, Nullable<MyStruct<int>>, bool> func =
(value, nullableValue) => value == nullableValue;
func(new MyStruct<int>(), null);
The above runs with no errors.
Update 3: Seems that removing the IEquatable<>
interface doesn't prevent the exception, so the code can be further simplified.