Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast uint to Int32

Tags:

c#

casting

I'm trying to retrieve data from MSNdis_CurrentPacketFilter, my code looks like this:

ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\WMI",
                "SELECT NdisCurrentPacketFilter FROM MSNdis_CurrentPacketFilter");

foreach (ManagementObject queryObj in searcher.Get())
{
     uint obj = (uint)queryObj["NdisCurrentPacketFilter"];
     Int32 i32 = (Int32)obj;
}

As you can see, I'm casting the received object from NdisCurrentPacketFilter twice, which begs the question: why??

If I try to cast it directly to int, e.g.:

Int32 i32 = (Int32)queryObj["NdisCurrentPacketFilter"];

It throws an InvalidCastException. Why is that?

like image 685
Eli Avatar asked Dec 20 '22 06:12

Eli


1 Answers

Three things contribute to this not working for you:

  • The type of NdisCurrentPacketFilter is uint, according to this link.

  • Using the indexer queryObj["NdisCurrentPacketFilter"] returns an object, which in this case is a boxed uint, the value of NdisCurrentPacketFilter.

  • A boxed value type can only be unboxed into the same type, i.e. you must at least use something like:

    • (int)(uint)queryObj["NdisCurrentPacketFilter"]; (i.e. a single-line version of what you're already doing), or

    • Convert.ToInt32, which uses IConvertible to perform the cast, unboxing it to uint first.


You can reproduce the same problem as in your question with something like

object obj = (uint)12345;
uint unboxedToUint = (uint)obj; // this is fine as we're unboxing to the same type
int unboxedToInt = (int)obj; // this is not fine since the type of the boxed reference type doesn't match the type you're trying to unbox it into
int convertedToInt = Convert.ToInt32(obj); // this is fine
like image 162
Wai Ha Lee Avatar answered Jan 04 '23 22:01

Wai Ha Lee