Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

4. Types and References: It’s 10:00. Do ... > Even when a number is the right size...

Even when a number is the right size, you can’t just assign it to any variable

Let’s see what happens when you try to assign a decimal value to an int variable.

Do this

  1. 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);
  2. Try building your program. Uh oh—you got an error that looks like this:

    image with no caption
  3. 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:

    image with no caption

So what happened?

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.

Note

Take a minute to flip back to the beginning of the last chapter and check out how you used casting when you passed the NumericUpDown. Value to the Talker Tester form.

Sharpen your pencil Solution

Three of these statements won’t compile, either because they’re trying to cram too much data into a small variable or because they’re putting the wrong type of data in. Circle them.

image with no caption