0

I've researched about IEnumerable and IEnumerator there's a lot of way on how to make a class useable for foreach statement. But that doesn't answer my question. Why is the EventLogEntryCollection used in foreach loop does not return EventLogEntry? But if I changed var to EventLogEntry it works the way I expected using for loop.

       EventLog eventLog1 = new EventLog
        {
            Log = myLogName,
            Source = "sourcy"
        };

        EventLogEntryCollection collection = eventLog1.Entries;
        eventLog1.Close();

        foreach (var v in collection)
        {
            Console.WriteLine(v.Message); //object does not contain definition for Message

        }

        for (int i = 0; i < collection.Count; i++)
        {
            Console.WriteLine("The Message of the EventLog is :"
               + collection[i].Message);
        }
Ronald Abellano
  • 774
  • 10
  • 34

1 Answers1

3

Why does the EventLogEntryCollection used in foreach loop not return EventLogEntry?

Because it's old code, pre-generics. It merely implements ICollection, which inherits the non-generic IEnumerable.GetEnumerator() method used by your foreach() loop.

So the item type of that enumerator is object, and that doesn't contain a Message property.

But if I changed var to EventLogEntry it works the way I expected using for loop.

That's exactly what you need to do to fix this.

See also Object type not recognised on foreach loop.

CodeCaster
  • 147,647
  • 23
  • 218
  • 272
  • 1
    Absolutely perfect answer. Doc link for reference https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.eventlogentrycollection?view=netframework-4.7.2 – Rahul Apr 15 '19 at 09:38