Variables & Types
Static typing vs dynamic typing
Introduction
In this lesson, you'll learn about variables & types in C#. Coming from Python, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In Python, you're familiar with static typing vs dynamic typing.
C# has its own approach to static typing vs dynamic typing, 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; // compile-time constant
// var — type inference
var city = "Istanbul"; // inferred as string
// Types cannot change
int x = 42;
// x = "string"; // compile error
// Nullable
int? maybeAge = null;
string? maybeName = null;Comparing to Python
Here's how you might have written similar code in Python:
name = "Alice"
age = 30
score = 9.5
active = True
MAX = 100 # constant by convention
# Type hints (optional)
city: str = "Istanbul"
# Variables can change type
x = 42
x = "now a string" # validYou may be used to different syntax or behavior.
C# types are fixed at declaration; Python types are dynamic
You may be used to different syntax or behavior.
C# var infers type (still fixed); Python variables can change type
You may be used to different syntax or behavior.
C# const is compile-time; Python UPPER_CASE is just convention
You may be used to different syntax or behavior.
C# nullable types (int?) explicitly allow null; Python uses None freely
Step-by-Step Breakdown
1. Explicit Types
C# requires a type for every variable. The compiler verifies assignments at compile time — no runtime type errors.
age = 30int age = 30;2. var Inference
C#'s var infers the type from the initializer — like Python's dynamic typing but the type is still fixed after declaration.
var name = "Alice"; // string, immutable type
var count = 0; // int, immutable type3. Nullable Types
C# distinguishes between int (never null) and int? (can be null). Python's None can be assigned to any variable.
age = None # any variable can be Noneint? age = null; // explicitly nullable
int required = 30; // cannot be nullCommon Mistakes
When coming from Python, developers often make these mistakes:
- C# types are fixed at declaration; Python types are dynamic
- C# var infers type (still fixed); Python variables can change type
- C# const is compile-time; Python UPPER_CASE is just convention
Key Takeaways
- C# types fixed at declaration; Python dynamic
- var infers type but keeps it fixed
- int? for nullable; int for non-nullable
- C# const is compile-time; Python UPPER_CASE is convention