Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
Let’s see what happens when you try to assign a decimal value to an int variable.
Do this
Create a new project and add a button to it. Then add these lines to the button’s Click() method:
decimal myDecimalValue = 10;
int myIntValue = myDecimalValue;
MessageBox.Show("The myIntValue is " + myIntValue);Try building your program. Uh oh—you got an error that looks like this:
Make the error go away by casting the decimal to an int. Once you change the second line so it looks like this, your program will compile and run:
The compiler won’t let you assign a value to a variable if it’s the wrong type—even if that variable can hold the value just fine—because that’s the underlying cause behind an enormous number of bugs. When you use casting, you’re essentially making a promise to the compiler that you know the types are different, and that in this particular instance it’s OK for C# to cram the data into the new variable.