Variables & Data Types
What Is a Variable?
A variable is like a labeled jar in your kitchen. You stick a label on it (the name), decide what kind of stuff goes inside (the type), and then put something in it (the value). In C#, every jar has a strict rule about what it can hold — you can't pour soup into a jar labeled "cookies."
C# is a statically typed language, which means you pick the jar type before you fill it. This catches mistakes early — like trying to do math with someone's name.
Declaring Variables
The Common Types
Here are the types you'll use every single day:
int— whole numbers like42or-7. Holds roughly ±2 billion.long— whenintisn't big enough. Think national debt numbers.double— decimal numbers like3.14. Great for science, but can have tiny rounding errors.decimal— decimal numbers for money. Slower but super precise. Always use this for cash!string— text (internally a character array), wrapped in double quotes:"hello".bool— justtrueorfalse. Like a light switch.char— a single character in single quotes:'Z'.
There's also var — it lets C# figure out the type for you. It's not lazy; it's just shorthand. The type is still locked in at compile time.
var, const, and Bigger Numbers
Type Casting — Changing Jar Types
Sometimes you need to pour data from one jar into a different-shaped jar. C# has two ways:
- Implicit casting — automatic and safe. Going from a small jar to a bigger one:
int→long→double. - Explicit casting — you force it with
(type). Going from big to small can lose data, so you have to say "I know what I'm doing."
You can also use Convert.ToInt32(), int.Parse(), or int.TryParse() to convert strings to numbers.