CS1579 - - foreach statement cannot operate on variables of type 'object'

wire_jp 216 Reputation points
2023-03-13T16:01:55.2133333+00:00

Hello,

I have the following C# code in the ContactsViewModel.cs of a .NET MAUI app: -


 public void ReadContacts()
        {
            var contacts = Contact.GetContacts();
            Contacts.Clear();
            foreach (var contact in contacts) 
// contacts has a red squiggly line beneath it and the Error message is: Error 1579 - foreach statement cannot operate on variables of type 'object' because 'object' does not contain a public instance or extension definition for 'GetEnumerator'
            {
                Contacts.Add(contact);
            }
        }



Developer technologies .NET .NET MAUI
Developer technologies C#
{count} votes

Accepted answer
  1. Alessandro Caliaro 4,196 Reputation points
    2023-03-14T05:35:15.29+00:00

    Contact is not a List, so you can not foreach. If your string contains a list of contacts (maybe separated with commas) you could use "Split" to split the contacts to a list of strings

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2023-03-13T20:04:16.8366667+00:00

    Contact.GetContacts() is returning an object.

    you can not enumerate an object. if the object implement enumerable you can cast, but if not, it will throw an error.

    if seems a design flaw that Contact.GetContacts() return an object rather than an a strongly typed enumerable.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.