Variables and Data Types
Variables and Data Types
Section titled βVariables and Data TypesβWhat it means
Section titled βWhat it meansβ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).
Examples
Section titled βExamplesβint age = 30; // explicit typevar 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 changereadonly DateTime Created; // set once, typically in a constructor, then never reassigned
// Value types vs reference typesint x = 5;int y = x; // y gets its OWN COPY of the valuey = 10;Console.WriteLine(x); // 5 -- unaffected, since int is a value typeCommon mistake
Section titled βCommon mistakeβ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 initializedQuick practice
Section titled βQuick practiceβ-
Is
varin C# the same kind of βdynamicβ typing asvarin JavaScript?Answer
No β C#'svaris inferred once at compile time and the variable remains strictly, statically typed afterward; it's purely a syntax convenience, not dynamic typing. -
Whatβs the difference between
constandreadonly?Answer
constvalues must be known at compile time and can never change;readonlyfields can be assigned once at runtime (typically in a constructor) and are then fixed for the object's lifetime. -
If
int y = x;copies a value type, does changingyafterward affectx?Answer
No β value types are copied by value, soxandybecome completely independent after the assignment.