Sirop4ik
Sirop4ik

Reputation: 5243

How to cast correctly from long to int?

I have such method

        public int foo()
        {
            return (int) MainJsonValues[JsonKeys.DP_PORT.Value];
        }

This method should make cast and return this value

There is how I call this method

myObj.foo()

So, it is very strange because as we can see value contains in Dictionary

You can see my debug on screenshot

enter image description here

So, as far as I see this method can't convert from long to int...

Error

enter image description here

What am I doing wrong?

Upvotes: 1

Views: 346

Answers (1)

Eric Lippert
Eric Lippert

Reputation: 660108

A boxed value type may only be unboxed to the unboxed type or the nullable unboxed type. That is, if you have a boxed long, you may unbox it to long or long?, but not any other type. (See the comments for details.)

Therefore you need to do the conversion in two steps:

object x = 1L; // boxed long
long y = (long)x; // unboxed
int z = (int)y;

Upvotes: 8

Related Questions