πŸ“Œ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

JavaScriptC# Equivalent
letnormal variable (int x = 5;)
constconst (compile-time) / readonly (runtime)
var (JS)Not the same! In C#, var = implicit typing
β€”dynamic (runtime typing)