Skip to main content

03. Variables and Data Types in C#

Level: Beginner

ℹ️ What You'll Learn
  • 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:

PartMeaning
intType of data: whole number
ageVariable name
16Value 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:

TypeStoresExampleUse in School System
intWhole number101Roll number, age, count
stringText"Sahasra Kumar"Name, email, class name
doubleDecimal number87.5Percentage, average marks
decimalMoney15000.00mFees, salary, payment
booltrue/falsetrueActive, passed, paid
charSingle character'A'Section, grade
DateTimeDate and timeDateTime.NowJoining 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" or 123

Step 1: Store Student Text Data

Use string for text.

string studentName = "Sahasra Kumar";
string className = "10-A";
string parentPhone = "9876543210";

Important:

  • string values use double quotes.
  • Phone number is usually string, not int, 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 OK
  • decimal: 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:

  • isActive
  • hasPaidFees
  • isPresent
  • hasPassed

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

💻 Try It — Console App
💡 Paste into Program.cs and press F5⌥ GitHub
string studentName = "Sahasra Kumar";
int rollNumber = 101;
string className = "10-A";
char section = 'A';
int age = 16;
double percentage = 87.5;
decimal totalFees = 30000.00m;
decimal paidAmount = 15000.00m;
bool isActive = true;
DateTime enrolledOn = DateTime.Now;

decimal balanceFees = totalFees - paidAmount;

Console.WriteLine("=== Student Details ===");
Console.WriteLine($"Name: {studentName}");
Console.WriteLine($"Roll Number: {rollNumber}");
Console.WriteLine($"Class: {className}");
Console.WriteLine($"Section: {section}");
Console.WriteLine($"Age: {age}");
Console.WriteLine($"Percentage: {percentage}");
Console.WriteLine($"Total Fees: {totalFees}");
Console.WriteLine($"Paid Amount: {paidAmount}");
Console.WriteLine($"Balance Fees: {balanceFees}");
Console.WriteLine($"Active: {isActive}");
Console.WriteLine($"Enrolled On: {enrolledOn:dd-MM-yyyy}");

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 true or false.
  • It is safer for real applications.

Quick Data Type Rules

NeedUse
Student namestring
Roll numberint
Percentagedouble
Feesdecimal
Active or inactivebool
Grade letterchar
Joining dateDateTime

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 (always decimal)
  • Attendance: date, isPresent (always bool)
  • Teacher: name, salary, joiningDate

Why strong typing matters:

  • string studentName prevents storing numbers as names
  • decimal fees prevents money calculation errors
  • bool isPresent prevents confusion (yes/no only)
  • DateTime ensures 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:

  1. Change student name to your name
  2. Change roll number to 201
  3. Change class to "10-B"
  4. Change total fees to 40000
  5. Change paid amount to 25000
  6. Run and see balance fees calculated automatically

See how variables store data and string interpolation displays it.


ℹ️ Video Tutorial

Variables and data types explained with live examples. Video coming soon. Subscribe to NexCoding YouTube for updates.


Best Practices

  1. Use meaningful names like studentName, not x.
  2. Use int for normal whole numbers.
  3. Use double for marks and percentages.
  4. Use decimal for money.
  5. Use bool names that sound like yes/no questions.
  6. Use explicit types while learning.
  7. Use TryParse for user input.
  8. 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

QuestionAnswer
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

🎯 Q1: What is a variable in C#?

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.

🎯 Q2: Why does every variable need a data type?

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.

🎯 Q3: What is the difference between int, double, and decimal?

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;
🎯 Q4: What is the difference between string and char?

string stores text with one or more characters.

char stores exactly one character.

Example:

string name = "Sahasra";
char section = 'A';
🎯 Q5: What is var in C#?

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.

🎯 Q6: Why is TryParse safer than Parse?

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 AI to Learn Faster
⚠️ Important for beginners: Do NOT use AI to write your code yet. Type every example yourself. Your brain learns by doing, not by reading AI output. Use AI only to explain and quiz you — not to code for you. Once you have strong fundamentals, AI becomes a powerful productivity tool for repetitive tasks.

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.

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.


Next Article

Operators and Expressions ->

nexcoding.in