π1. Declaration
In C#, variables are declared with a type. See 1.1 Data Types
int age = 25; // Explicit type
var name = "Alice"; // Implicit typing (compiler infers type)
const double Pi = 3.14159; // Constant
readonly int Year; // Can assign only once (constructor or declaration)
π2. Scope
C# variable scope depends on where you declare it:
- Local variable β inside a method or block (
{}
), only accessible there.
void Test() { int x = 10; // only inside Test }
- Class-level fields β accessible inside the class (depending on access modifier).
class Person { private string name; // field, only inside class }
- Static variables β belong to the class, not an instance.
static int counter = 0;
- Global variables donβt really exist in C#, but you can simulate them with
static
fields.
π3. Mutability
C# doesnβt have let
/const
exactly like JavaScript, but hereβs the mapping:
Normal variable (mutable)
csharp
int x = 10; x = 20; // β
Allowed
const
(compile-time constant, immutable)
-
Must be assigned at declaration.
-
Value is baked into code.
csharp
const double Gravity = 9.81; // Gravity = 10; // β Error: cannot reassign
readonly
(immutable after initialization, runtime constant)
-
Assigned at declaration or in the constructor.
-
Useful for values not known at compile time.
readonly int StartYear; public Example() { StartYear = DateTime.Now.Year; // β
Allowed (once in constructor) }
var
(mutable, but type fixed)
- Type is inferred, but still strongly typed.
var age = 30; // inferred as int age = 40; // β
OK // age = "hi"; // β Error: type mismatch
dynamic
(mutable, type flexible at runtime)
dynamic anything = 10; anything = "Hello"; // β
Works, but unsafe
π4. Variable Lifetime
-
Local variables β exist until the method ends.
-
Instance fields β exist as long as the object exists.
-
Static fields β exist for the lifetime of the application domain.
πQuick Mapping to JavaScript for Clarity
JavaScript | C# Equivalent |
---|---|
let | normal variable (int x = 5; ) |
const | const (compile-time) / readonly (runtime) |
var (JS) | Not the same! In C#, var = implicit typing |
β | dynamic (runtime typing) |