Variables, Constants (const/readonly), var & Scope Masterclass
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.
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.
// 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.
| Feature | const | readonly |
|---|---|---|
| Evaluation Time | Compile-Time constant | Runtime constant |
| Initialization | MUST be initialized at declaration | Can be initialized at declaration OR inside a Constructor |
| Static Behavior | Implicitly static | Can be instance-level (different per object) |
| Allowed Types | Primitive types, enums, strings only | Any data type (including complex classes & arrays) |
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}");
// 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
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.