Menu
CoddyTech

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 icon

Challenge

Beginner

The tracker will show how much you spent. Give the count and the total their own variables.

  1. At the top of Program.cs, declare var count = 0; and var total = 0m;.
  2. Change the second Console.WriteLine to print count with string interpolation: $"{count} expenses". It still prints 0 expenses.
  3. 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.00

Try 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");
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in C# and .NET Basics