03. Variables and Data Types in C#
Level: Beginner
- What a variable is
- Why every variable needs a data type
- Common C# data types used in real projects
- Store student data using variables
- Display variables using
Console.WriteLine - Convert text input into numbers safely
- Common mistakes beginners make with variables
In the previous article, you created and ran your first C# program.
Now we need to store data.
In a School Management System, we need values like:
- Student name
- Roll number
- Class name
- Marks
- Fees
- Pass/fail status
To store these values in C#, we use variables.
The Problem: Where Do We Keep Data in Code?
Imagine a student record:
Name: Sahasra Kumar
Roll Number: 101
Class: 10-A
Marks: 87.5
Fees Paid: 15000.00
Active: Yes
C# needs a separate named place to store each value.
string studentName = "Sahasra Kumar";
int rollNumber = 101;
string className = "10-A";
double marks = 87.5;
decimal feesPaid = 15000.00m;
bool isActive = true;
Each line creates one variable.
What is a Variable?
A variable is a named box in memory that stores a value.
Variable name Value
-------------------------
studentName -> Sahasra Kumar
rollNumber -> 101
marks -> 87.5
isActive -> true
Basic syntax:
dataType variableName = value;
Example:
int age = 16;
Meaning:
| Part | Meaning |
|---|---|
int | Type of data: whole number |
age | Variable name |
16 | Value stored in the variable |
Why Data Types Matter
C# is a strongly typed language.
That means each variable must clearly say what type of data it stores.
int rollNumber = 101; // whole number
string name = "Sahasra"; // text
double percentage = 87.5; // decimal number
bool hasPassed = true; // true/false
This helps C# catch mistakes early.
Wrong:
int rollNumber = "Sahasra";
Why wrong?
rollNumber expects a number.
"Sahasra" is text.
Correct:
string studentName = "Sahasra";
Common Data Types
These are the main types beginners should know first:
| Type | Stores | Example | Use in School System |
|---|---|---|---|
int | Whole number | 101 | Roll number, age, count |
string | Text | "Sahasra Kumar" | Name, email, class name |
double | Decimal number | 87.5 | Percentage, average marks |
decimal | Money | 15000.00m | Fees, salary, payment |
bool | true/false | true | Active, passed, paid |
char | Single character | 'A' | Section, grade |
DateTime | Date and time | DateTime.Now | Joining date, date of birth |
Quick Definitions
- Variable - Named memory location storing a value
- Data Type - Category of data, such as text, number, true/false, or date
- String - Text data type
- Interpolation - Putting variable values inside text
- Type Safety - Preventing wrong data from being stored
- TryParse - Safe way to convert text to number
- Literal - A value written directly in code, like
"Sahasra"or123
Step 1: Store Student Text Data
Use string for text.
string studentName = "Sahasra Kumar";
string className = "10-A";
string parentPhone = "9876543210";
Important:
stringvalues use double quotes.- Phone number is usually
string, notint, because we do not calculate with it.
Wrong:
string studentName = Sahasra Kumar;
Correct:
string studentName = "Sahasra Kumar";
Step 2: Store Whole Numbers
Use int for whole numbers.
int rollNumber = 101;
int age = 16;
int totalStudents = 45;
Use int by default for normal whole numbers.
Step 3: Store Decimal Values
Use double for marks and percentages.
double marks = 87.5;
double percentage = 91.25;
Use decimal for money.
decimal totalFees = 30000.00m;
decimal paidAmount = 15000.00m;
decimal balance = totalFees - paidAmount;
Important:
double -> marks, percentage, average
decimal -> money
Why m is Needed on Decimal Values
Problem: C# needs to know: is 5000.00 a double or a decimal?
decimal fees = 5000.00; // Wrong - ambiguous type
decimal fees = 5000.00m; // Correct - 'm' says "this is decimal"
The m stands for "money decimal". It tells C#: "This is a precise money value, not a general decimal number."
Why does this matter for School Management System?
double: Good enough for marks (87.5%) - small rounding error is OKdecimal: Precise for money (Rs. 30000.50) - rounding error is NOT OK
Example:
double percentage = 87.5; // OK: small rounding error acceptable
decimal fees = 30000.50m; // OK: precise money value
decimal wrongFees = 30000.50; // Error: need 'm'
Beginner rule: Whenever you store money, always use m at the end.
Step 4: Store True or False
Use bool when the answer is yes/no.
bool isActive = true;
bool hasPaidFees = false;
bool hasPassed = true;
Common names:
isActivehasPaidFeesisPresenthasPassed
Step 5: Store One Character
Use char for one character.
char section = 'A';
char grade = 'B';
Important:
char -> single quotes: 'A'
string -> double quotes: "A"
Step 6: Store Dates
Use DateTime for dates.
DateTime dateOfBirth = new DateTime(2009, 5, 15);
DateTime enrolledOn = DateTime.Now;
Meaning:
new DateTime(2009, 5, 15)
Year = 2009
Month = 5
Day = 15
Full Example: Student Variables
Expected output:
=== Student Details ===
Name: Sahasra Kumar
Roll Number: 101
Class: 10-A
Section: A
Age: 16
Percentage: 87.5
Total Fees: 30000.00
Paid Amount: 15000.00
Balance Fees: 15000.00
Active: True
Enrolled On: 24-05-2026
Your date may be different.
String Interpolation
String interpolation means putting variable values inside a message.
Why Use String Interpolation?
Without $ (concatenation - harder to read):
string name = "Sahasra";
int marks = 87;
Console.WriteLine("Student " + name + " scored " + marks + " marks.");
Problem: Too many quotes and + signs. Hard to see the sentence.
With $ (interpolation - easier to read):
string name = "Sahasra";
int marks = 87;
Console.WriteLine($"Student {name} scored {marks} marks.");
Better: Reads like normal sentence. Variables clearly marked with { }.
Output (both give same result):
Student Sahasra scored 87 marks.
How to Use String Interpolation
string studentName = "Priya";
int age = 16;
decimal fees = 30000.00m;
Console.WriteLine($"Name: {studentName}");
Console.WriteLine($"Age: {age} years");
Console.WriteLine($"Fees: {fees}");
Remember:
Use $ before the string.
Put variables inside { }.
This works with all data types: string, int, decimal, bool, DateTime.
Changing Variable Values
A variable value can change.
int marks = 80;
Console.WriteLine(marks);
marks = 90;
Console.WriteLine(marks);
Output:
80
90
Constants
Use const when the value should not change.
const int PassingMarks = 35;
const int MaxMarks = 100;
Wrong:
const int PassingMarks = 35;
PassingMarks = 40;
This gives an error because constants cannot be changed.
var Keyword
var lets C# decide the type from the value.
var studentName = "Sahasra"; // string
var rollNumber = 101; // int
var percentage = 87.5; // double
But for beginners, explicit types are clearer:
string studentName = "Sahasra";
int rollNumber = 101;
double percentage = 87.5;
Beginner rule:
Use explicit types while learning.
Use var later when the type is obvious.
Type Conversion
Sometimes user input comes as text.
Example:
string marksInput = "85";
But to calculate, we need a number.
int marks = int.Parse(marksInput);
Better and safer:
string marksInput = "85";
if (int.TryParse(marksInput, out int marks))
{
Console.WriteLine($"Marks: {marks}");
}
else
{
Console.WriteLine("Invalid marks entered.");
}
Why TryParse is better:
- It does not crash for bad input.
- It gives
trueorfalse. - It is safer for real applications.
Quick Data Type Rules
| Need | Use |
|---|---|
| Student name | string |
| Roll number | int |
| Percentage | double |
| Fees | decimal |
| Active or inactive | bool |
| Grade letter | char |
| Joining date | DateTime |
When You'll Use This in SMS
Variables are building blocks. Every SMS feature uses them.
In School Management System:
- Student:
name,rollNumber,className,dateOfBirth - Exam:
marks,totalMarks,percentage - Fees:
totalFees,paidAmount,balance(alwaysdecimal) - Attendance:
date,isPresent(alwaysbool) - Teacher:
name,salary,joiningDate
Why strong typing matters:
stringstudentName prevents storing numbers as namesdecimalfees prevents money calculation errorsboolisPresent prevents confusion (yes/no only)DateTimeensures date format always consistent
Right data types = SMS never stores wrong data = real system reliability.
Common Mistakes (3 Critical)
Mistake 1: Using text without quotes
Wrong:
string name = Sahasra;
Correct:
string name = "Sahasra";
Mistake 2: Using double for money
Wrong:
double fees = 5000.00;
Correct:
decimal fees = 5000.00m;
Mistake 3: Mixing string and int
Wrong:
string marks = "85";
int total = marks + 10;
Correct:
int marks = 85;
int total = marks + 10;
Try This Now
Run the student details example above. Then experiment:
- Change student name to your name
- Change roll number to 201
- Change class to "10-B"
- Change total fees to 40000
- Change paid amount to 25000
- Run and see balance fees calculated automatically
See how variables store data and string interpolation displays it.
Variables and data types explained with live examples. Video coming soon. Subscribe to NexCoding YouTube for updates.
Best Practices
- Use meaningful names like
studentName, notx. - Use
intfor normal whole numbers. - Use
doublefor marks and percentages. - Use
decimalfor money. - Use
boolnames that sound like yes/no questions. - Use explicit types while learning.
- Use
TryParsefor user input. - Keep one variable for one clear purpose.
Practice Task
Create variables for one teacher:
Teacher Name: Meena Rao
Employee Id: 501
Subject: Mathematics
Experience: 8 years
Salary: 45000.00
Is Active: true
Joining Date: today's date
Print the teacher details using Console.WriteLine.
Expected starter:
string teacherName = "Meena Rao";
int employeeId = 501;
string subject = "Mathematics";
int experienceYears = 8;
decimal salary = 45000.00m;
bool isActive = true;
DateTime joiningDate = DateTime.Now;
Console.WriteLine("=== Teacher Details ===");
Console.WriteLine($"Name: {teacherName}");
Console.WriteLine($"Employee Id: {employeeId}");
Console.WriteLine($"Subject: {subject}");
Console.WriteLine($"Experience: {experienceYears} years");
Console.WriteLine($"Salary: {salary}");
Console.WriteLine($"Active: {isActive}");
Console.WriteLine($"Joining Date: {joiningDate:dd-MM-yyyy}");
Quick Revision
| Question | Answer |
|---|---|
| What is a variable? | A named place to store a value |
| Which type stores text? | string |
| Which type stores whole numbers? | int |
| Which type stores money? | decimal |
| Which type stores true/false? | bool |
| Which method safely converts text to int? | int.TryParse |
A variable is a named memory location used to store a value.
Example:
int age = 16;
string name = "Sahasra";
Here, age stores a whole number and name stores text.
C# is strongly typed. The data type tells the compiler what kind of value can be stored.
Example:
int marks = 85;
string studentName = "Sahasra";
This prevents mistakes like storing text inside a number variable.
int stores whole numbers.
double stores decimal numbers like marks or percentages.
decimal stores money values.
Example:
int rollNumber = 101;
double percentage = 87.5;
decimal fees = 15000.00m;
string stores text with one or more characters.
char stores exactly one character.
Example:
string name = "Sahasra";
char section = 'A';
var lets the compiler decide the variable type from the assigned value.
Example:
var name = "Sahasra"; // string
var age = 16; // int
While learning, explicit types are usually clearer.
Parse throws an error if the input is invalid.
TryParse returns true or false, so the program can handle invalid input safely.
Example:
if (int.TryParse("85", out int marks))
{
Console.WriteLine(marks);
}
Use ChatGPT, Claude, or Copilot to go deeper on C# variables and data types. Try these prompts:
"Explain variables and data types with School Management examples""Give me 10 practice questions for int, string, double, decimal, bool, and DateTime""Explain why decimal is better than double for money""Quiz me with 5 beginner questions about C# variables"
💡 Tip: After reading this article, paste your own code into AI and ask "What could go wrong here and why?" — fastest way to find edge cases and deepen understanding.
C# Section Links
Use these links to continue the full Backend > C# topic from the top menu:
Target search terms for this lesson: c# variables and data types, c# int string bool, c# var keyword.