I have a feeling the answer is no after reading through documentation. However, I am trying to find out whether it’s possible to know if a type supports relational operators, such as: <, >, >= etc…
I am looking to do something like:
Func<MyObject, object> greaterThan = obj => obj > 10;
var results = myList.Where(greaterThan).ToList();
As I may be searching on different properties, it might be decimal, int or float. I am doing this in an MVC action so, as far as I know, it can’t support generics. I can obviously move it out and have a generic implementation, but I’d like to know this answer first.
To elaborate, implicit operator overloading isn’t feasible. The reason being is that property is not known until runtime (sorry should of mentioned that). Consequently nor can generics be used. Given any property, I need to check that it’s not 0. This is a somewhat contrived example of my current implementation that seems to be working (not fully tested):
Func<MyObject, IComparable> prop = obj => isOn ? obj.DecimalVal : obj.IntValue;
Func<MyObject, bool> clause = obj => prop(obj).CompareTo(0) != 0;
var results = myList.Where(clause);
I’m just hoping that CompareTo will return 0; even if the prop evaluates a decimal which has a value of 0, when compared to the int 0 – despite these being different types.
UPDATE
I clearly had my hopes set too high, the above approach failed. Therefore, the solution I am using for now is not desirable but it’s working. I would love to hear a more elegant approach.
Func<MyObject, dynamic> prop = obj => isOn ? obj.DecimalVal : obj.IntValue;
Func<MyObject, bool> clause = obj => prop(obj) != 0;
var results = myList.Where(clause);
No. In C#, operators are static members of the types, so they can’t be part of an interface.
There is one way for your code to work in C# 4:
dynamic:This will work whether
myListis a collection ofints,doubles ordecimals. (But beware,resultsis of typeList<dynamic>.)But .Net actally provides some interfaces that can be used for the same purposes operators are commonly used for: comparing for equality (
IEquatable<T>) and comparing for which element is greater and which is smaller (IComparable<T>). With those, you can write code like this: