Christof Lindner
Christof Lindner

Reputation: 1

C# | Converting ushort[] to IEnumerable<object> doesnt work

To my situation: Im reading with ManagementObjectSearcher objects and want to print them to a NameValueCollection (desriptor.Properties). In order to achive this I need to iterate though every given data and write it to the collection - if it is an array of any type I also need to iterate through every element of this array. FYI: I use the NameValueCollection because it necessary for the code later on.

So I tried:

ManagementObjectCollection searchResults = new ManagementObjectSearcher(
        "select * from " + key).Get(); // for testing use => "Win32_ComputerSystem"
int counter = 0;
foreach (ManagementBaseObject? searchResult in searchResults) {
    if (searchResult is null)
        continue;

    counter += 1;
    foreach (PropertyData? property in searchResult.Properties) {
        if (property.Name is null) {
            continue;
        }

        object tmpobj = searchResult.GetPropertyValue(property.Name);
        string propertyname = counter + " | " + property.Name;
        if (tmpobj is null) {
            continue;
        }
        else if (tmpobj is IEnumerable<object> tmpcollection) {
            foreach (object item in tmpcollection) {
                if (tmpobj is null) {
                    continue;
                }
                else {
                    descriptor.Properties.Add(propertyname, item.ToString());
                }
            }
        }
        else {
            descriptor.Properties.Add(propertyname, tmpobj.ToString());
        }
    }
}

Since every array should inherit from "IEnumerable" and any Datatype including struct should inherit "object", i figured it should work, but for some reason it doesn't for structs (at least for double, short, ushort etc.). (FYI: I'm using the latest .Net8)

my info from microsoft to structs [16.4.3 Inheritance]: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/structs

For easier testing the following code can be used:

short[] shorts =
{
    11,
    22,
    33,
    623,
    2321,
    0
};
short shorter = 0;

object objshorts = shorts as object;

if (shorts is IEnumerable<short>) ; // => true
if (shorts is IEnumerable<ValueType>) ;// => false
if (shorts is IEnumerable<object>) ; // => false
if (shorter is object) ; // => true

My questions are:

Upvotes: 0

Views: 47

Answers (0)

Related Questions