Pete
Pete

Reputation: 10871

decimals, ints, casting... oh my!

I'm going through the "Head First C#" book and in one of the chapters I created a program and uses variables declared as ints and decimals. Visual Studio got cranky with me a couple of times about mixing and matching the two. For example:

dinnerParty.NumberOfPeople = (int) numericUpDown1.Value;

NumberOfPeople is declared as an int and apparently numeric updowns are decimals.

Also, the book puts an M after some numbers when adding them together. For example:

public void SetHealthyOption(bool healthy)
{
    if (healthy)
    {
        CostOfBeveragesPerPerson = 5.00M;
    }
    else
    {
        CostOfBeveragesPerPerson = 20.00M;
    }
}

CostOfBeveragesPerPerson is declared as a decimal.

So I have two specific questions:

1) How can you know when you need to cast something? I'm sure there is quite a bit to casting... can anyone provide some good links to learn about casting?

2) What does the M after the numbers do?

EDIT

So the M denotes that the number is a decimal and not a double. Why not just cast the number as a decimal like: (decimal) 50.00? And what is that "function" called? If I wanted to see what "letters" were available what would I google?

Upvotes: 3

Views: 752

Answers (3)

RossFabricant
RossFabricant

Reputation: 12502

Type    Suffix          Example
uint    U or u          100U
long    L or l          100L
ulong   UL or ul        100UL
float   F or f          123.45F
decimal M or m          123.45M

There's a lot of pages that explain C# numeric literals. The letter at the end is not a cast or any kind of function. It is syntax showing that what you are writing represents a value of a particular type. So writing (decimal) 5.0 uses a cast, but writing 5.0m does not.

Upvotes: 4

Alexander Kahoun
Alexander Kahoun

Reputation: 2488

  1. Here's a good link on casting straight from MSDN.
  2. The M tells the compiler that the number is a decimal, otherwise it will assume it to be a double

Upvotes: 2

Turnor
Turnor

Reputation: 1856

  1. Explicit casts are generally needed when there's a loss of precision between the two types. For example, if you had an int and assigned it to a long, no cast is necessary since long can hold all values that an int can. If you were assigning a long to an int, however, a cast would be required as int can hold less values than a long can, which can lead to data loss.
  2. The M defines the number as a Decimal type. If you omit this, the number is interpreted as a double.

Upvotes: 6

Related Questions