Variables & Constants

🔷 C# Programming Lesson 2 Beginner

C# is a statically-typed language, meaning every variable must be declared with a specific data type beforehand. C# provides primitive numerical variables, booleans, and a high-precision decimal type.

1 Core Data Types & Decimal Precision

Standard data types in C# include:

  • `int` (4 bytes): Standard integer.
  • `double` (8 bytes): Standard decimal float.
  • `float` (4 bytes): Single-precision decimal (requires `f` suffix, e.g. `3.14f`).
  • `decimal` (16 bytes): High-precision financial decimal type. **Must append `m` suffix** (e.g. `19.99m`). Offers no rounding errors, making it the industry standard for banking applications.
  • `bool` (1 byte): Stores `true` or `false`.
  • `char` (2 bytes): Unicode character.

Implicitly Typed Variables (`var`): You can use the `var` keyword to let the compiler determine the variable type based on the assigned value. Once declared, its type is locked and cannot change.

2 Variables Code

Let's run a program declaring types, casting, and printing variables:

C# — Variables & Constants ▶ Run Code
using System;

class Program {
    static void Main() {
        int age = 25;
        double pi = 3.14159;
        decimal price = 19.99m; // Financial decimal with 'm' suffix
        const double TaxRate = 0.08; // Immutable constant

        // Implicit typing
        var message = "C# is fun!";

        Console.WriteLine("Age: " + age);
        Console.WriteLine("Price: $" + price);
        Console.WriteLine("Constant Tax Rate: " + TaxRate);
        Console.WriteLine("Var Message: " + message);
    }
}
3 Code Challenge
Challenge: Write a program declaring a `const` decimal representing discount percentages. Calculate the discounted price of a product costing `99.99m` and output the calculated price.