Variables & Types
Static typing and type declarations
Introduction
In this lesson, you'll learn about variables & types in C#. Coming from JavaScript, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In JavaScript, you're familiar with static typing and type declarations.
C# has its own approach to static typing and type declarations, which we'll explore step by step.
The C# Way
Let's see how C# handles this concept. Here's a typical example:
string name = "Alice";
int age = 30;
double score = 9.5;
bool active = true;
const int Max = 100;
// var — type inference
var city = "Istanbul"; // inferred as string
// Types cannot change
int x = 42;
// x = "hello"; // compile error!
// Nullable types
int? maybeAge = null;Comparing to JavaScript
Here's how you might have written similar code in JavaScript:
let name = "Alice";
let age = 30;
let score = 9.5;
let active = true;
const MAX = 100;
// Types can change
let x = 42;
x = "hello"; // valid in JSYou may be used to different syntax or behavior.
C# is statically typed; variable types cannot change after declaration
You may be used to different syntax or behavior.
JS let/const → C# type declarations or var (inferred)
You may be used to different syntax or behavior.
C# has bool (not JS's truthy/falsy); int, double, string are primitive types
You may be used to different syntax or behavior.
C# nullable types (int?) explicitly mark optional values
Step-by-Step Breakdown
1. Type Declarations
In C# every variable has a fixed type. The compiler verifies type correctness at compile time, catching errors before runtime.
let age = 30;int age = 30;2. var Inference
C#'s var infers the type from the right side — like JS let, but the type is still fixed after declaration.
var name = "Alice"; // string, fixed
var count = 0; // int, fixed3. Nullable Types
C#'s ? suffix makes value types nullable, replacing JS's undefined/null pattern for optional values.
int? age = null;
if (age.HasValue) Console.WriteLine(age.Value);
int result = age ?? 0; // null-coalescing like JS ??Common Mistakes
When coming from JavaScript, developers often make these mistakes:
- C# is statically typed; variable types cannot change after declaration
- JS let/const → C# type declarations or var (inferred)
- C# has bool (not JS's truthy/falsy); int, double, string are primitive types
Key Takeaways
- C# types are fixed at declaration
- var infers type but does not allow type changes
- int? makes value types nullable
- ?? null-coalescing works the same as JS