1

I want to be able to determine if a passed argument is an IEnumerable.

static bool TestForEnumerable(dynamic toTest)
{
    return toTest is IEnumerable<Object>;
}

I wrote the following console app to investigate a problem I as having ...

static void Main(string[] args)
{
    Program _program = new Program();
    Console.WriteLine("");

    List<TestObject> toObj = new List<TestObject>
        {
            new TestObject { FirstName = "James", MiddleName = "Maitland", LastName = "Stewart", DOB = new DateTime(1908, 05, 20), IsFemale = false },
            new TestObject { FirstName = "Gary", MiddleName = "James", LastName = "Cooper", DOB = new DateTime(1901, 05, 07), IsFemale = false },
            new TestObject { FirstName = "Archibald", MiddleName = "Alec", LastName = "Leach", AKA="Cary Grant", DOB = new DateTime(1904, 01, 18), IsFemale = false },
            new TestObject { FirstName = "Erol", MiddleName = "Leslie Thompson", LastName = "Flynn", DOB = new DateTime(1909, 06, 20), IsFemale = false },
            new TestObject { FirstName = "Humphrey", MiddleName = "DeForest", LastName = "Bogart", DOB = new DateTime(1899, 12, 25), IsFemale = false },
            new TestObject { FirstName = "Marion", MiddleName = "Robert", LastName = "Morrison", AKA="John Wayne", DOB = new DateTime(1907, 05, 26), IsFemale = false },
        };

    var kvpObj = new List<KeyValuePair<string, string>>
        {
            new KeyValuePair<string, string>("GPC", "3"),
            new KeyValuePair<string, string>("CENTRAL CONTRACT", "4"),
            new KeyValuePair<string, string>("N/A", "2"),
            new KeyValuePair<string, string>("--Select Item--", "-1"),
        };

    Console.WriteLine(String.Format("List<TestObject> is IEnumerable : {0}", TestForEnumerable(toObj)));
    Console.WriteLine(String.Format("List<KeyValuePair<string, string>> is IEnumerable : {0}", TestForEnumerable(kvpObj)));

}

The out put of this test was ...

List<TestObject> is IEnumerable : True
List<KeyValuePair<string, string>> is IEnumerable : False

So the question is ... These are both Lists which implement IEnumerable. Why is the List of KeyValuePairs not considered an IEnumerable?

Gary O. Stenstrom
  • 2,284
  • 9
  • 38
  • 59

1 Answers1

10

It isn't IEnumerable<object>, because KeyValuePair<TKey, TValue> is a value-type (struct), and generic variance rules doesn't allow for value-types and object to be interchangeable during type tests (as a conversion - boxing - is required).

So: while it isn't IEnumerable<object>, it is, however, IEnumerable in the non-generic sense.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900