Skip to content

Variables and Data Types

A variable is a named storage location with a specific type, declared once and (unless const/readonly) reassignable afterward. C# is statically typed β€” every variable’s type is known and checked at compile time, either written explicitly (int age = 30;) or inferred with var (var age = 30;, still strictly typed as int, just written more concisely).

int age = 30; // explicit type
var name = "Alice"; // inferred as string -- var is NOT the same as JavaScript's `var`
double price = 19.99;
bool isActive = true;
string message = $"Hi {name}, you are {age}"; // string interpolation
const double Pi = 3.14159; // compile-time constant, can never change
readonly DateTime Created; // set once, typically in a constructor, then never reassigned
// Value types vs reference types
int x = 5;
int y = x; // y gets its OWN COPY of the value
y = 10;
Console.WriteLine(x); // 5 -- unaffected, since int is a value type

Assuming var makes C# dynamically typed, like JavaScript’s var or Python β€” var is purely a compile-time convenience; the variable’s type is still fixed and fully checked, it’s just inferred from the initializer instead of written out.

var count = 5;
// count = "five"; // Error: cannot convert 'string' to 'int' -- `count` is still strictly typed as int!
// `var` requires an initializer, since the type must be inferred from something
// var x; // Error: implicitly-typed variables must be initialized
  1. Is var in C# the same kind of β€œdynamic” typing as var in JavaScript?

    AnswerNo β€” C#'s var is inferred once at compile time and the variable remains strictly, statically typed afterward; it's purely a syntax convenience, not dynamic typing.
  2. What’s the difference between const and readonly?

    Answerconst values must be known at compile time and can never change; readonly fields can be assigned once at runtime (typically in a constructor) and are then fixed for the object's lifetime.
  3. If int y = x; copies a value type, does changing y afterward affect x?

    AnswerNo β€” value types are copied by value, so x and y become completely independent after the assignment.