I am trying to write a generic comparison routine. However, some of the items in my class are in Collections and I need to enumerate to compare.
Is there an easy way, without a try/catch block to determine is a variable supports GetEnumerator()
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The answers suggesting you check to see if the object is an
IEnumerableare reasonably spot on. It’s going to be the case the overwhelming majority of the time that your collection or object will implement that interface if it supports enumeration. But it is not required.For something to be enumerated in a
foreach, it really only needs to expose aGetEnumerator()method that returns an object with suitableMoveNext()andCurrentimplementations. Consider something like:You can put
new CustomCollection()into a loop and get the values 1..10.By all means, check for the interface first. If that’s all you want to support, fine. If you want to go that extra mile, you’d need to perform steps like the compiler would, as in check for the appropriate methods and return types. Here’s a thoroughly untested draft of an implementation.
Some quick tests in LinqPad, but by no means exhaustive…