CodeBlanks Logo Icon CodeBlanks

Summary - Variables

C# course · Beginner · Lesson 12/116

Declare typed variables to write a small profile program.

Summary

In this unit you learned the basics of C# variables. Let's put them all together.

We saw four core types: int for whole numbers, double for decimals, string for text and bool for true-false.

You used var to let the compiler infer the type and const to define fixed values. You also learned camelCase and PascalCase naming, plus scope and lifetime.

Now let's code a few short exercises that combine these ideas.

Exercise Compute the tax

Declare const int TaxPercent with 18. Declare int price with 100. Compute tax as price * TaxPercent / 100. Compute total as price + tax. Print total with Console.WriteLine.

Show example solution
Start with const int TaxPercent = 18;, then add int price = 100; int tax = price * TaxPercent / 100; int total = price + tax;.
Example solution:
const int TaxPercent = 18;
int price = 100;
int tax = price * TaxPercent / 100;
int total = price + tax;
Console.WriteLine(total);

Exercise Print player info

Assign "Alex" to string playerName, 5 to int level, and true to bool isLoggedIn. Print the three variables on separate lines with Console.WriteLine.

Show example solution
First write string playerName = "Alex"; int level = 5; bool isLoggedIn = true; then add three Console.WriteLine calls.
Example solution:
string playerName = "Alex";
int level = 5;
bool isLoggedIn = true;
Console.WriteLine(playerName);
Console.WriteLine(level);
Console.WriteLine(isLoggedIn);

Test yourself

  1. Keyword for a constant

    ____ int MaxPlayers = 4;
    Show answer
    const int MaxPlayers = 4;
  2. Which line throws an error?

    const int Max = 10;
    int count = 5;
    Max = 20;
    count = 15;
    • const int Max = 10;
    • Max = 20;
    • int count = 5;
    • count = 15;
    Show answer

    Max = 20; — Correct! You cannot reassign a const variable; Max = 20; is an error.

All lessons in Beginner