Search code examples
c#castingstrong-typing

Why can't I pull a ushort from a System.Object and then cast it as a uint? (C#)


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?


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.