Variables, Constants (const/readonly), var & Scope Masterclass

โšก C# 12 & .NET 8 ๐ŸŸข Chapter 4 of 35 ๐Ÿ“‚ Phase 2: Variables & Scope ๐Ÿ“… 2026 Edition
๐Ÿ“Œ Covered in this chapter: Variable Fundamentals ยท Declaration & Initialization ยท Naming Rules ยท const vs readonly ยท var vs dynamic ยท Scope Levels ยท Type Inference

Welcome to Phase 2 (Chapter 4): C# Variables, Constants, Scope & Type Inference Masterclass! A variable is a named memory location used to store data during execution. In this chapter, we master variable declaration, initialization, assignment, reassignment, variable naming rules (camelCase vs PascalCase), const vs readonly constants, implicit typing with var, dynamic typing with dynamic, and scope levels.

1Variable Declaration, Initialization & Naming Rules

In C#, every variable must have a declared data type before it can be used. Accessing an unassigned local variable results in a compile error.

C# โ€” Variable Operations โ–ถ Run in Compiler
// 1. Declaration (datatype variableName;)
string name;

// 2. Initialization (assigning initial value)
name = "Ravi";

// 3. Declaration & Initialization combined
int age = 21;
double price = 99.99;
bool isStudent = true;

// 4. Reassignment (updating value)
age = 22;

Console.WriteLine($"Name: {name}, Age: {age}, Price: {price:C}, IsStudent: {isStudent}");

C# Naming Conventions & Rules:

โ€ข camelCase: Use camelCase for local variables and method parameters (e.g., userAge, totalPrice).

โ€ข PascalCase: Use PascalCase for Classes, Structs, Methods, Properties, and Enums (e.g., StudentName, CalculateTax).

โ€ข Allowed Characters: Letters, digits, and underscores. Must start with a letter or underscore.

2Constants โ€” const vs readonly
Featureconstreadonly
Evaluation TimeCompile-Time constantRuntime constant
InitializationMUST be initialized at declarationCan be initialized at declaration OR inside a Constructor
Static BehaviorImplicitly staticCan be instance-level (different per object)
Allowed TypesPrimitive types, enums, strings onlyAny data type (including complex classes & arrays)
C# โ€” const vs readonly โ–ถ Run in Compiler
class BankAccount
{
    public const double INTEREST_RATE = 0.05; // Compile-time constant
    public readonly string AccountNumber;    // Runtime constant

    public BankAccount(string accNum)
    {
        AccountNumber = accNum; // Set at runtime in constructor!
    }
}

BankAccount acc = new BankAccount("ACC-98765");
Console.WriteLine($"Rate: {BankAccount.INTEREST_RATE}, Account: {acc.AccountNumber}");
3var vs dynamic
C# โ€” var vs dynamic โ–ถ Run in Compiler
// 1. var: Implicitly Typed Local Variable (STRICTLY TYPE-SAFE at compile time!)
var city = "Hyderabad"; // Compiler infers type: string
var count = 100;         // Compiler infers type: int
// city = 50;            // COMPILE ERROR! Cannot convert int to string.

// 2. dynamic: Bypasses compile-time type checking (evaluated at RUNTIME)
dynamic data = "Hello";
Console.WriteLine($"Length: {data.Length}"); // 5
data = 42; // Allowed! Type changes to int at runtime
4Technical FAQs

Q1: Does using 'var' make C# dynamic or slow?

No! var is 100% strongly typed and has ZERO performance penalty. The Roslyn compiler replaces var with the exact type at compile time.