CodingNeed.

1 · Values and control flow · 25 MIN

Types, expressions and methods

Types express a program’s data contract before execution.

C# uses static types, even when var lets the compiler infer a local type. This example uses decimal for a small monetary calculation and the m suffix for decimal literals. Decimal still requires a rounding and currency policy in a real payment system. The pure Total method returns a number; formatting occurs only at the output boundary. InvariantCulture makes the teaching output independent of the machine’s decimal separator, an important distinction between internal values and localized display.

Keep decimal calculation separate from culture-sensitive text.

Read the example

using System;
using System.Globalization;
decimal Total(decimal price, int quantity) => price * quantity;
var amount = Total(12.50m, 2);
Console.WriteLine(amount.ToString("F2", CultureInfo.InvariantCulture));
Console.WriteLine(Total(12.50m, 0).ToString("F2", CultureInfo.InvariantCulture));
Check the expected output
25.00
0.00

Your challenge

Add a discount method that validates a 0–100 percentage and states a two-decimal rounding rule.

Solution cost: O(1) fixed-size decimal arithmetic. time · O(1) auxiliary state. space

Common trap

var is inferred static typing, not a dynamically typed variable.

Study the project implementation
using System;
using System.Globalization;
decimal Total(decimal price, int quantity) => price * quantity;
var amount = Total(12.50m, 2);
Console.WriteLine(amount.ToString("F2", CultureInfo.InvariantCulture));
Console.WriteLine(Total(12.50m, 0).ToString("F2", CultureInfo.InvariantCulture));

Further reading: Official documentation

Next lesson: Collections, loops and LINQ

Essential cookies keep your account signed in. Optional analytics is not configured on this site. Your choice does not affect access to lessons.

Read the Privacy Policy. You can change this choice in the footer.