Skip to content

Instantly share code, notes, and snippets.

Created May 28, 2013 17:20
Show Gist options
  • Save anonymous/5664417 to your computer and use it in GitHub Desktop.
Save anonymous/5664417 to your computer and use it in GitHub Desktop.
Code for reproducing exception described in http://stackoverflow.com/q/16797890/562906
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Reflection;
namespace ConsoleApplication1
{
struct MyStruct
{
private readonly int _value;
public MyStruct(int val) { this._value = val; }
public override bool Equals(object obj) { return false; }
public override int GetHashCode() { return base.GetHashCode(); }
public static bool operator ==(MyStruct a, MyStruct b) { return false; }
public static bool operator !=(MyStruct a, MyStruct b) { return false; }
}
struct MyGenericStruct<T>
{
private readonly int _value;
public MyGenericStruct(int val) { this._value = val; }
public override bool Equals(object obj) { return false; }
public override int GetHashCode() { return base.GetHashCode(); }
public static bool operator ==(MyGenericStruct<T> a, MyGenericStruct<T> b) { return false; }
public static bool operator !=(MyGenericStruct<T> a, MyGenericStruct<T> b) { return false; }
}
class Program
{
// Utility method for declaring Expression<Func<..>> without typing out the entire type each time
static Expression<Func<T, U, bool>> MakeExpr<T, U>(Expression<Func<T, U, bool>> expr)
{
return expr;
}
static void Main(string[] args)
{
// Non generic struct
Expression<Func<MyStruct, MyStruct, bool>> exprA =
(valueA, valueB) => valueA == valueB;
Expression<Func<MyStruct?, MyStruct?, bool>> exprB =
(nullableValueA, nullableValueB) => nullableValueA == nullableValueB;
Expression<Func<MyStruct?, MyStruct, bool>> exprC =
(nullableValueA, valueB) => nullableValueA == valueB;
// Generic struct
Expression<Func<MyGenericStruct<int>, MyGenericStruct<int>, bool>> exprGA =
(valueA, valueB) => valueA == valueB;
Expression<Func<MyGenericStruct<int>?, MyGenericStruct<int>?, bool>> exprGB =
(nullableValueA, nullableValueB) => nullableValueA == nullableValueB;
// Causes InvalidOperationException:
Expression<Func<MyGenericStruct<int>?, MyGenericStruct<int>, bool>> exprGC =
(nullableValueA, valueB) => nullableValueA == valueB;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment