Question

I'm manipulating the items in a list that's a System.Management.ManagementObjectCollection. Each of these items is a System.Management.ManagementObject which contains properties indexed by string. See:

foreach (ManagementObject queryObj in searcher.Get())
{
    string osversion = (string)queryObj["Version"];
    string os = (string)queryObj["Name"];
    uint spmajor = (uint)queryObj["ServicePackMajorVersion"];
    uint spminor = (uint)queryObj["ServicePackMinorVersion"];
    ...
    ...
    ...
}

Each "dictionary access" to queryObj returns a C# object which is in fact whatever the property is supposed to be -- I have to know their "real" type beforehand, and that's OK.

Problem is, I get a InvalidCastException in the uint casts. I have to use the real type, which is ushort. Shouldn't a cast from ushort to uint be acceptable and obvious?

In this case, I'll eventually convert the values to string, but what if I had to get them into uint or int or long variables?

Was it helpful?

Solution

You're attempting to unbox a ushort, and it can only be unboxed to a ushort.

Once you've unboxed it you can then cast it as normal.

Any boxed value of type T can only be unboxed to a T (or a Nullable).

Eric Lippert did a very good blog post about this exact thing here.

OTHER TIPS

The problem with the casting operator is it really means two things: cast and convert. You can convert a value from a number to a different number, but you cannot cast a boxed number to the wrong type of number. Thus, what you'd have to do instead is:

uint spmajor = (uint)(ushort)queryObj["ServicePackMajorVersion"];

Better yet:

uint spmajor = Convert.ToUInt32(queryObj["ServicePackMajorVersion"]);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top