Search code examples
c#arraysstringwmi

Printing values from a System.String[] using foreach loop


My goal is to get the IP addresses alongside the NIC names, Here is my sample code, I want to get the value of the IPAddress object which is of type System.String[], I see a lot of internet post and try to copy their code for a foreach loop, but it is not working for me, what could be the problem?

I am still getting used to the foreach loop since it is new to me just this week

My error is highlighted at the foreach Error which is :

foreach statement cannot operate on variables of type 'object' because 'object' does not contain a public definition for 'GetEnumerator'

ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from Win32_NetworkAdapterConfiguration ");

int ram = 1;
foreach (ManagementObject obj in searcher.Get())
{
     if (obj["MACAddress"] != null)
     {
         Console.WriteLine(String.Format("NIC #{0}:", ram));

         if (obj["IPAddress"] != null) // IPAddress is of type System.String[]
         {
             foreach (string s in obj["IPAddress"])
             { 
                 Console.WriteLine(s);         
             }   
         }
     }
}

Solution

  • This error is telling you that obj["IPAddress"] is returning an object and that foreach doesn't know how to iterate through an object.

    Therefore, you must first cast your obj to an iterable collection :

     String[] addresses = (String[])obj["IPAddress"];
     foreach (string s in addresses)
     { 
         Console.WriteLine(s);         
     }
    

    Taken from msdn documentation:

    The foreach statement repeats a group of embedded statements for each element in an array or an object collection that implements the System.Collections.IEnumerable or System.Collections.Generic.IEnumerable interface.

    Hence the fact that foreach isn't supported for the object type.