Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if object is any Predicate<T>

I've got an IList<Delegate> that contains some Func<bool>s and some Predicate<T>s, where T varies. I later need to sort out which of these items are Predicate<T>s, but don't want to close the door to adding other Delegate types to the list later, so I do not want to do this by identifying objects by !(current_delegate is Func<bool>).

The highest abstraction below Predicate<T> is MulticastDelegate, which seems unhelpful (would need a non-generic Predicate type under Predicate<T>), and identifying the presence of the generic parameter is also useless given the other generic Delegates that may be present in the list.

The only other thing I've considered is checking the Name of the Type. To me, string comparison is a near-smell, but maybe that is the is the best and/or only way -- you tell me.

What is the best way to definitively determine that an object is any Predicate<T> without knowing the type of T?

like image 230
Jay Avatar asked Feb 23 '10 17:02

Jay


2 Answers

Like this:

obj.GetType().GetGenericTypeDefinition() == typeof(Predicate<>)
like image 182
SLaks Avatar answered Sep 19 '22 00:09

SLaks


Predicate<int> pred = ...;
var isPreidcate = pred.GetType().GetGenericTypeDefinition() == typeof(Predicate<>);

On another note, if you have a generic list, you shoulnd't need to check the types in it. You may want to rethink your design if you need to check for specific types within a list.

like image 32
BFree Avatar answered Sep 19 '22 00:09

BFree