how to convert int to uint

The problem is that int is stored as object. Int derives from object but uint doesn't derive from int so you can't cast int stored as object to uint. First you have to cast it to int and then to uint because that cast is valid. Try it yourself:

object o = 5;//this is constant that represents int, constant for uint would be 5u
uint i = (uint)o;//throws exception

But this works:

object o = 5;
int i = (int)o;
uint j = (uint)i;

or

object o = 5;
uint i = (uint)(int)o; //No matter how this looks awkward 

It's possible that the Index property is returning a String or something. You could do the following:

var num = Convert.ToUInt32(data[structure["MICROSECONDS"].Index]);

Convert.ToUInt32 is overloaded with all the relevant types that a uint can be converted from.


First of all you should check the type of your value. You can do it by calling obj.GetType() method (either in your code directly or in Immediate window).

If it is int then you can do:

uint u = (uint) (int) obj;

Please note that it differs from your cast because it casts to int and then converts to uint while you were trying to cast to uint. int cannot be cast to uint and that is why you get the InvalidCastException. int can be only converted to uint. It is confusing that both conversion and cast operators look same in code: u = (uint) x.

Easier thing you can do is calling a specific method from Convert class:

uint u = Convert.ToUInt32(x);

Tags:

C#