views:

80

answers:

1

Hi.

Is there a way of forcing the C# compiler to ignore missing operator overloads for objects, and instead handle that check in runtime? I ask because I have a container that has multiple objects that has various attributes of type int, string, ushort and so on. I'm making a search function for that container, and would like to be able to search on various fields.

I'm using predicates and lambda expressions.

This is what I want: var data = container.Retrieve(ID => (ID == 5), Date => (Date > somedate)); assuming ID and Date are fields in the container's objects

This is what I have to do today (It works, though): var data = container.Retrieve(ID => ((int)ID == 5), Date => ((DateTime)Date > somedate));

That extra casting is not very good looking compared to the first example, I'd like to not have to do it. I'd like to have the option to check this in runtime instead.

Is there any way of accomplishing this?

Thanks, Hallgeir

+3  A: 

No, C# 3.0 has no support for operators without knowing the type.

In C# 4.0 you can do it with dynamic, but it is slower.

In your case, you know what the types should be - so just cast (like you are).


In the more general case:

With unknown types, look at Comparer.Default.Compare and object.Equals...

With generics; look at Comparer<T>.Default.Compare(x,y) - that should do everything you need for >,>=,< and <= (including nulls etc). Likewise EqualityComparer<T>.Default.Equals(x,y) handles == and != (including nulls etc).

For more operators (+,-,* etc) - look at MiscUtil

Marc Gravell
Alright, then I'll live with my casts.Cheers for the quick answer. :)
Hallgeir