Var and Interpolation
Part of the C# and .NET Basics section of Coddy's ASP.NET Core journey. Lesson 2 of 20.
A modern C# program declares most local variables with var. The compiler reads the type from the value on the right, so var cups = 2; makes an int. The type is still fixed: cups can never hold a string later. Money gets the decimal type, written with an m after the number, because decimal stores 0.1 exactly and double does not.
A string that starts with $ is an interpolated string: each {...} is replaced by the value inside it. After a colon comes a format, and F2 means two decimals:
var item = "Flat white";
var price = 3.5m;
var cups = 2;
Console.WriteLine($"{cups} x {item}: {price * cups:F2}");This prints 2 x Flat white: 7.00.
Challenge
BeginnerThe tracker will show how much you spent. Give the count and the total their own variables.
- At the top of
Program.cs, declarevar count = 0;andvar total = 0m;. - Change the second
Console.WriteLineto printcountwith string interpolation:$"{count} expenses". It still prints0 expenses. - Add a third line that prints the total with two decimals, using
{total:F2}.
The program prints exactly these three lines:
Expense Tracker
0 expenses
Total: 0.00Try it: press Run. You see the three lines. Change 0m to 12.5m and Run again: the last line reads Total: 12.50. Put it back to 0m before you press Check.
Try it yourself
Console.WriteLine("Expense Tracker");
Console.WriteLine("0 expenses");
This lesson includes a short quiz. Start the lesson to answer it and track your progress.