Implicit conversion

Implicit conversion is done by the compiler automatically. It's done by the compiler without any intervention or command from the developer. The following two conditions must be fulfilled for a compiler to execute implicit type conversion:

  •  No data loss: The compiler must determine that if it executes the conversion implicitly, there will be no data loss. In Chapter 2Understanding Classes, Structures, and Interfaces, in the Data Types section, we saw that each data type acquires a space in memory. Therefore, if we try to assign a variable with the type as float, which acquires 32 bytes of memory, to double, which acquires 64 bytes of memory, we can be sure that there won't be any data loss in the conversion.

  • No chance of cast exception: The compiler must determine that there is no chance of an exception during the casting of the value from one data type to another. For example, if we try to set a string value to a float variable, the compiler will not do the implicit conversion as it would be an invalid cast.

Now, let's look at the following code implementation to see how implicit conversion works in C#:

 int i = 100;
float f = i;

In the preceding code example, we have declared a variable, i, of the int type and have assigned it a value of 100. In the next statement, we have declared a variable, f, of the float type and have assigned it the value in i

Now, the compiler would determine that both the required conditions for implicit conversions are being met, that is, float acquires more memory than int and there is no chance of an invalid cast exception—an int value is also a valid value in a float variable. Hence, the compiler gives no error and does the implicit conversion. 

However, if we do the reverse, which is trying to assign a float value in int, the compiler will determine that the conditions are not being fulfilled and will give us a compile-time error. Please refer to the following screenshot:

However, in certain circumstances, even if there is a chance of data loss, we would still like to have those conversions. C# provides us with explicit conversion, which allows us to explicitly instruct the compiler to let the conversion take place. Let's go through how explicit conversion takes place.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.5.15