Cant cast float to int if object

This code works fine

float ff = 5.5f; int fd = (int) ff; Console.Write(fd); 

Where does this code not work

 float ff = 5.5f; object jf = ff; int fd = (int) jf; Console.Write(fd); 

What rule in the runner causes this?

+8
casting c #
source share
2 answers

You can use float for int, but you cannot use float in box for int - you need to unpack it first.

 int fd = (int)(float)jf; 

Read Eric Lippert's "Presentation and Identification" in more detail.

+13
source share
 float ff = 5.5f; object jf = ff; int fd = (int) jf; 

here, when you put from a float into an object, the actual type that jf is a float, and you free the box marked directly in int, which is not accepted by the runtime.

so you need to unzip the contents for float first and then add it back to int.

+6
source share

Source: https://habr.com/ru/post/649826/


All Articles