Variables and data types
Store values in named boxes, choose the right type for each value, and learn the rules for names, constants and var.
int age = 25; // type name = value;string name = "Ravi";double height = 1.75;bool isStudent = true; Console.WriteLine(name + " is " + age);Ravi is 25
See it in memory
The built-in types you will use most
| Type | Holds | Size | Example |
|---|---|---|---|
int | int count = 10; | ||
long | long views = 9000000000L; | ||
double | double pi = 3.14159; | ||
float | float speed = 2.5f; | ||
decimal | decimal price = 199.99m; | ||
bool | true or false | bool isOpen = false; | |
char | char grade = 'A'; | ||
string | string city = "Salem"; |
Declare, assign, change
int score; // declare (create the box)score = 50; // assign (put a value in)score = score + 10; // change it: read 50, add 10, store 60Console.WriteLine(score);60
Naming rules and conventions
Must start with a letter or _, then letters, digits or_. No spaces.Cannot be a keyword like intorclass.Case-sensitive: ageandAgeare different variables.Convention: local variables use camelCase: firstName,totalPrice.Use meaningful names: studentCountis far better thanscorx.
var: let the compiler work out the type
var count = 10; // intvar price = 99.5; // doublevar name = "Ravi"; // string// count = "ten"; // error: count is still an int!var is not a “any type” box. The type is fixed at compile time from the value on the right. Use it when the type is obvious from the right-hand side.
Constants
const double Pi = 3.14159;const int MaxStudents = 60;// MaxStudents = 70; // error: a const can never changeValue types and reference types (first look)
int, double, bool, char and decimal are value types: the box holds the value itself. string is a reference type: the box holds a reference (an address) to the text stored elsewhere, on the heap. You will see why this matters when we study classes and memory.
Show the solution
string productName = "Steel Beam";decimal price = 1499.50m;int stock = 12;bool isAvailable = true; Console.WriteLine(productName);Console.WriteLine(price);Console.WriteLine(stock);Console.WriteLine(isAvailable);Steel Beam 1499.50 12 True
Remember
A variable is a named, typed box: type name = value;.Pick the type by the data: int,double,decimal,bool,char,string.Assign before you read; names are camelCase and case-sensitive. varinfers a fixed type;constvalues never change.