I have an object that holds a number greater than zero(granted). Let’s give it 42. It’s originally part of a HttpContext.Session collection.
Session["myNumber"] = 42;
object obj = Session["myNumber"];
I’ve tried using it as an int with casting:
int num = (int)obj;
This returns 0.
However, I managed to get what I want doing:
int num = int.Parse(obj.ToString());
This gives me 42.
Does this make sense, might it be a problem with declarations or types or something?
What you describe simply doesn’t happen.
If you get the value
0when unboxing an object, then the object actally contains a boxedint, and it actually has the value0.The only way to unbox a value is to use the exact type of the value, which means that you would get an exception if it was anything other than an
int.There has to be something else in your code that causes this.