C #: from the basics to the medium level (Type Convertion & Overflow)
Now talk about type conversion.
There are two type of conversion : implicit and explicit.
The first is when we declare one type and pass it in another type.
If we loook at this example
I pass a byte value into int and into float, and this is perfectly fine.
Why?
Because the type byte goes from 0 to 255,
while interger goes from -2.147.483.648 to 2.147.483.647
and float from 1,175494351 E — 38 to 3,402823466 E + 38
Because the destination type can contain the starting byte value, we don’t have any data loss.
But if we try to pass a int into byte
We have an error.
Now, technically we can pass 10 byte into int, the problem is that VisualStudio every time we try to pass one type into another that cannot contain that type of value return us an error.
Because it compare the type, non the value we try to pass.
Byte can contain only number until 255, int 2.147.483.647.
So we can’t pass int 10 into byte?
Of course we can do!
But we need what we call explicit cast.
The syntax for explicit cast is
We need to open parentheses and inside we pass the type we need for cast.
Watch out when we use explicit cast : we know 10 can be contain in a byte type and we don’t lose any data, but if we pass 1000
VisualStudio compile EVEN IF WE CAN LOSE SOME DATA.
If we start the application, it runs without “problems”, but we lost some data.
As we can see, we have strange result.
This happen because during conversion we lost some data.
This is the concept of OVERFLOW.
Make a simple example :
First we need a checked keyword to try this.
Inside checked, we try to do this
If we try ti run it
We have System.OverflowException.
This because we try to pass a value of 256 in a type that can contain only 255.
But when we convert with explicit cast, VisualStudio “trust us”, so we need to pay attention when use explicit cast.
Another thing to know is:
we can explicitly try to pass one type of value into another, but with this cast they must be “compatible”.
We pass a int to byte, or a int to float, but we connot make this
Because a string can’t be explicit cast as int.
But there are specific type conversion in C#
We have the Convert class to convert the type.
Or we can use the Parse() method of the int class.