Ephesians 5:1-2 (NIV)
“Follow God’s example, therefore, as dearly loved children and walk in the way of love, just as Christ loved us and gave himself up for us as a fragrant offering and sacrifice to God.”
This program will demonstrate the importance of type casting in the C# language. It is based off of this documentation by Microsoft.
Enter the following code to follow along —
Here, we have two int variables.
These two int variables are named “integer_Number_1” & “integer_Number_2”.
We have a third variable, of data-type double named “quotient_Number”.
Variable “quotient_Number” will divide “integer_Number_1” from “integer_Number_2”.
In otherwords:
variable “quotient_Number” will calculate the results of “777” divided by “770”.
The problem is that . . .
The outcome will be incomplete . . .
It will be technically wrong. . . .
Does 777 / 770 = 1 ?
Let’s put it in a calculator:
Therefore, we see: 770 / 770 = 1.009090909090909 . . . .
HOW DO WE FIX THIS?
We introduce Type Casting.
Casting allows data to be temporarily converted by the compiler.
We will cast from the int data type to the decimal data type.
The decimal data type will tell the compiler to give us an outcome that has decimal values.
This is the output of our modified program code:
So, what changed?
(1) In our new variable “quotient_Number_with_Decimal”, the data type was changed to decimal.
Now, this change alone would NOT be enough.
At least one of the numbers being divided, needs to be temporarily cast into the decimal data type.
(2) Therefore, the equation “integer_Number_1” / “integer_Number_2” is changed as follows:
“(decimal)integer_Number_1” / “(decimal)integer_Number_2”
*** The “(decimal)” code is the code that tells the compiler the data type is being temporarily transformed from an int to a decimal.
To summarize:
(1) Data-type casting allows the compiler to temporarily convert the data-type of a variable.
(2) Data-type casting uses “( )” with the new data-type inside the parenthesis, like this: “(decimal)” or “(int)” or “(float)”.
(3) This conversion is only temporary. The compiler will still recognize the variable as it’s old data-type in other areas of the program.
Ephesians 5:1-2 (NIV)
“Follow God’s example, therefore, as dearly loved children and walk in the way of love, just as Christ loved us and gave himself up for us as a fragrant offering and sacrifice to God.”
Leave a Reply