0% found this document useful (0 votes)
8 views20 pages

C# Variable Basics and Best Practices

This document provides comprehensive study notes on C# variables, covering their definition, importance of data types, naming conventions, and various operations. It explains how to declare, modify, and print variable values, as well as incrementing techniques and the significance of proper initialization. Additionally, it includes FAQs and examples to illustrate key concepts and best practices in variable usage.

Uploaded by

ramchandra
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views20 pages

C# Variable Basics and Best Practices

This document provides comprehensive study notes on C# variables, covering their definition, importance of data types, naming conventions, and various operations. It explains how to declare, modify, and print variable values, as well as incrementing techniques and the significance of proper initialization. Additionally, it includes FAQs and examples to illustrate key concepts and best practices in variable usage.

Uploaded by

ramchandra
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

C# VARIABLES - STUDY NOTES

TABLE OF CONTENTS
1. What is a Variable?

2. Why Data Types are Important

3. Good Variable Names

4. Int vs Int32

5. [Link]()

6. Ways to Increment Variables

7. Uninitialized Variables

8. Primary Purpose of Variables

9. Declaring Integer Variables

10. Modifying Variable Values

11. The age++ Statement

12. Math Operations on Variables

13. Declaring Multiple Variables

14. Printing Variable Values

15. The age *= 2 Statement

FAQ SECTION

1. WHAT EXACTLY IS A VARIABLE?

Definition: A variable is a container that stores data in your computer's memory. Think of it as a labeled box
where you keep information.

Simple Analogy:

Variable = Box with a Label

📦 [age] → contains: 25
📦 [name] → contains: "Ali"
📦 [price] → contains: 99.99

Basic Syntax:
csharp

dataType variableName = value;

Examples:

csharp

// Storing different types of data


int age = 25; // Whole number
string name = "Muhammad"; // Text
double price = 99.99; // Decimal number
bool isStudent = true; // True/False
char grade = 'A'; // Single character

// Using variables
[Link](age); // 25
[Link](name); // Muhammad
[Link](price); // 99.99

Real-World Example:

csharp

// Student information
string studentName = "Ali";
int studentAge = 20;
double studentGPA = 3.8;
bool isPassed = true;

[Link]($"Name: {studentName}");
[Link]($"Age: {studentAge}");
[Link]($"GPA: {studentGPA}");
[Link]($"Passed: {isPassed}");

Why Variables?

Store data temporarily

Reuse values multiple times

Make code flexible and dynamic

Perform calculations

2. WHY ARE DATA TYPES IMPORTANT?


Definition: Data types tell the computer what KIND of data you're storing and how much memory to reserve.

Simple Analogy:

Like organizing a warehouse:


🍎 Fruit section (strings)
🔢 Number section (integers)
💰 Money section (decimals)
✅ Yes/No section (booleans)

Common Data Types:

csharp

// INTEGER TYPES (whole numbers)


byte age = 25; // 0 to 255
short year = 2024; // -32,768 to 32,767
int population = 100000; // -2 billion to 2 billion
long distance = 9999999999; // Very large numbers

// DECIMAL TYPES
float price = 10.5f; // 7 digits precision
double salary = 50000.50; // 15-16 digits precision
decimal money = 99.99m; // 28-29 digits (use for money!)

// TEXT TYPES
char grade = 'A'; // Single character
string name = "Ali"; // Multiple characters (text)

// BOOLEAN TYPE
bool isAdult = true; // true or false only

Why It Matters:

Example 1: Memory Efficiency

csharp

byte age = 25; // Uses 1 byte of memory


int age2 = 25; // Uses 4 bytes of memory
// Use byte if you know value is small (0-255)

Example 2: Precision

csharp
float price1 = 10.123456789f;
[Link](price1); // 10.12346 (rounds after ~7 digits)

double price2 = 10.123456789;


[Link](price2); // 10.123456789 (accurate!)

decimal price3 = 10.123456789m;


[Link](price3); // 10.123456789 (most accurate!)

Example 3: Wrong Type = Errors

csharp

// ❌ WRONG - Text in number variable


int age = "25"; // ERROR!

// ✅ CORRECT
int age = 25;
string ageText = "25";

Choosing Right Type:

csharp

// For ages, counts → int


int studentCount = 50;

// For prices, money → decimal


decimal productPrice = 29.99m;

// For scientific calculations → double


double pi = 3.14159265359;

// For names, addresses → string


string customerName = "John Doe";

// For yes/no, true/false → bool


bool isLoggedIn = false;

3. WHAT IS A GOOD NAME FOR A VARIABLE?

Rules for Good Variable Names:

✅ DO:
Use descriptive names

Start with lowercase letter (camelCase)

Use letters, numbers, underscore

Make it meaningful

❌ DON'T:
Start with number

Use spaces

Use C# keywords

Make it too short or too long

Examples:

csharp

// ❌ BAD NAMES
int x = 25; // What is x?
string s = "Ali"; // What is s?
int 1number = 10; // Can't start with number!
string first name = ""; // Can't have spaces!
int class = 5; // 'class' is C# keyword!

// ✅ GOOD NAMES
int studentAge = 25;
string studentName = "Ali";
double accountBalance = 1000.50;
bool isLoggedIn = true;
int numberOfStudents = 30;

Naming Conventions:

csharp
// camelCase (for variables, parameters)
int totalPrice = 100;
string firstName = "John";
bool isActive = true;

// PascalCase (for classes, methods)


class StudentManager { }
void CalculateTotal() { }

// UPPER_CASE (for constants)


const int MAX_STUDENTS = 100;
const string APP_NAME = "MyApp";

Be Descriptive:

csharp

// ❌ Too Short
int t = 100;
double p = 99.99;

// ✅ Just Right
int totalAmount = 100;
double productPrice = 99.99;

// ❌ Too Long
int theNumberOfStudentsCurrentlyEnrolledInTheClass = 50;

// ✅ Balanced
int enrolledStudents = 50;

Real-World Example:

csharp

// ❌ BAD
int a = 20;
int b = 30;
int c = a * b;

// ✅ GOOD
int length = 20;
int width = 30;
int area = length * width;
[Link]($"Area: {area}"); // Clear meaning!
4. WHAT HAPPENS IF I WRITE 'Int' INSTEAD OF 'int'?

Answer: ERROR! C# is case-sensitive. Int and int are different.

Explanation:

csharp

// ✅ CORRECT - lowercase 'int'


int age = 25;

// ❌ WRONG - uppercase 'Int'


Int age = 25; // ERROR: 'Int' does not exist

// Similarly:
string name = "Ali"; // ✅ CORRECT
String name = "Ali"; // ⚠️ Works but not recommended

double price = 99.99; // ✅ CORRECT


Double price = 99.99; // ⚠️ Works but not recommended

Technical Reason:

csharp

// 'int' is a C# keyword (alias)


int number1 = 10;

// 'Int32' is the actual .NET type


System.Int32 number2 = 10;

// They're the same, but use lowercase 'int'

Other Case-Sensitive Examples:

csharp
// ✅ CORRECT
bool isActive = true;
char grade = 'A';
float price = 10.5f;

// ❌ WRONG
Bool isActive = true; // ERROR
Char grade = 'A'; // ERROR
Float price = 10.5f; // ERROR

Remember: Always use lowercase for built-in types!

5. WHAT IS [Link]()?

Definition: [Link]() is a method that prints text to the console (command window/terminal).

Simple Analogy: Like a TV displaying what you tell it to show!

Basic Usage:

csharp

// Print simple text


[Link]("Hello, World!");

// Print numbers
[Link](100);
[Link](3.14);

// Print variables
int age = 25;
[Link](age); // 25

string name = "Ali";


[Link](name); // Ali

WriteLine vs Write:

csharp
// WriteLine - adds new line after printing
[Link]("First");
[Link]("Second");
// Output:
// First
// Second

// Write - stays on same line


[Link]("First ");
[Link]("Second");
// Output:
// First Second

String Interpolation (Modern Way):

csharp

string name = "Ali";


int age = 25;

// Old way
[Link]("My name is " + name + " and I am " + age);

// New way - String Interpolation (Better!)


[Link]($"My name is {name} and I am {age}");
// Output: My name is Ali and I am 25

Multiple Values:

csharp

int a = 10;
int b = 20;
int sum = a + b;

[Link]($"{a} + {b} = {sum}");


// Output: 10 + 20 = 30

Formatting Numbers:

csharp
double price = 99.99;
[Link]($"Price: ${price}");
// Output: Price: $99.99

int percentage = 85;


[Link]($"Score: {percentage}%");
// Output: Score: 85%

6. WHAT ARE THE VARIOUS WAYS TO INCREMENT A VARIABLE?

Definition: Incrementing means increasing the value of a variable.

All Methods:

csharp

int count = 10;

// Method 1: Simple addition


count = count + 1;
[Link](count); // 11

// Method 2: += operator (shorthand)


count += 1;
[Link](count); // 12

// Method 3: ++ operator (most common)


count++;
[Link](count); // 13

// Method 4: ++ prefix
++count;
[Link](count); // 14

Difference Between count++ and ++count:

csharp
// Postfix (count++) - use THEN increment
int a = 5;
int b = a++; // b gets 5, THEN a becomes 6
[Link]($"a = {a}, b = {b}"); // a = 6, b = 5

// Prefix (++count) - increment THEN use


int x = 5;
int y = ++x; // x becomes 6, THEN y gets 6
[Link]($"x = {x}, y = {y}"); // x = 6, y = 6

Increment by Other Values:

csharp

int score = 100;

// Add 5
score = score + 5; // 105
score += 5; // 110 (shorthand)

// Add 10
score += 10; // 120

// Double the value


score = score * 2; // 240
score *= 2; // 480 (shorthand)

Real-World Examples:

csharp

// Game score
int score = 0;
score += 10; // Player gets 10 points
score += 5; // Player gets 5 more points
[Link]($"Total Score: {score}"); // 15

// Counter in loop
int counter = 0;
counter++; // 1
counter++; // 2
counter++; // 3
[Link]($"Count: {counter}"); // 3
7. WHAT IF I DEFINE A VARIABLE BUT DON'T GIVE IT A VALUE?

Answer: You can declare it, but you MUST assign a value before using it.

Examples:

csharp

// Declaration without initialization


int age; // OK to declare

// ❌ WRONG - Can't use before assigning


[Link](age); // ERROR: Use of unassigned local variable

// ✅ CORRECT - Assign first, then use


int age;
age = 25;
[Link](age); // 25

Different Scenarios:

csharp

// Scenario 1: Declare and initialize together (Best!)


int count = 0;
[Link](count); // 0 ✅

// Scenario 2: Declare first, assign later


int total;
total = 100;
[Link](total); // 100 ✅

// Scenario 3: Conditional assignment


int result;
if (true)
{
result = 10;
}
[Link](result); // 10 ✅

// Scenario 4: Declare but never assign


int number;
// [Link](number); // ERROR! ❌

Class-Level vs Local Variables:

csharp
class Program
{
// Class-level: Auto-initialized to default
static int classVariable; // Default: 0

static void Main()


{
[Link](classVariable); // 0 (OK!)

// Local: MUST be initialized


int localVariable;
// [Link](localVariable); // ERROR! ❌

int localVariable2 = 0;
[Link](localVariable2); // 0 ✅
}
}

Default Values (Class-Level):

csharp

int number; // Default: 0


double price; // Default: 0.0
bool flag; // Default: false
string text; // Default: null

QUIZ SECTION - ANSWERS

1. WHAT IS THE PRIMARY PURPOSE OF A VARIABLE IN C#?

Answer: To store and manipulate data in a program.

csharp
// Store data
int age = 25;

// Manipulate data
age = age + 1; // Now 26

// Use in calculations
int birthYear = 2024 - age;

// Display data
[Link]($"Age: {age}");

2. WHICH OF THE FOLLOWING IS A CORRECT WAY TO DECLARE AN INTEGER VARIABLE?

Correct Ways:

csharp

// ✅ Method 1: Declare and initialize


int age = 25;

// ✅ Method 2: Declare only


int count;

// ✅ Method 3: Multiple at once


int a = 5, b = 10, c = 15;

// ✅ Method 4: Using var (type inference)


var number = 100; // Compiler knows it's int

Wrong Ways:

csharp

// ❌ No type
age = 25;

// ❌ Wrong type
string age = 25;

// ❌ Wrong syntax
int age == 25;
3. HOW CAN YOU MODIFY THE VALUE OF A VARIABLE?

Answer: By assigning a new value using the = operator.

csharp

// Initial value
int score = 100;
[Link](score); // 100

// Modify by assigning new value


score = 200;
[Link](score); // 200

// Modify using calculation


score = score + 50;
[Link](score); // 250

// Modify using shorthand


score += 25;
[Link](score); // 275

4. WHAT DOES THE STATEMENT age++; DO?

Answer: Increases the value of 'age' by 1.

csharp

int age = 25;


[Link](age); // 25

age++; // Increment by 1
[Link](age); // 26

age++; // Increment again


[Link](age); // 27

// Equivalent to:
age = age + 1;
// Or:
age += 1;
5. WHICH MATH OPERATIONS CAN YOU DO ON A VARIABLE?

Answer: Addition, Subtraction, Multiplication, Division, Modulus

csharp

int a = 10;
int b = 3;

// Addition
int sum = a + b; // 13

// Subtraction
int difference = a - b; // 7

// Multiplication
int product = a * b; // 30

// Division
int quotient = a / b; // 3 (integer division)
double exactDiv = (double)a / b; // 3.333...

// Modulus (remainder)
int remainder = a % b; // 1

[Link]($"Sum: {sum}");
[Link]($"Difference: {difference}");
[Link]($"Product: {product}");
[Link]($"Quotient: {quotient}");
[Link]($"Remainder: {remainder}");

Compound Operations:

csharp

int num = 10;

num += 5; // num = num + 5 → 15


num -= 3; // num = num - 3 → 12
num *= 2; // num = num * 2 → 24
num /= 4; // num = num / 4 → 6
num %= 4; // num = num % 4 → 2
6. IS IT POSSIBLE TO DECLARE MULTIPLE VARIABLES IN ONE LINE?

Answer: YES!

csharp

// ✅ Same type, same value


int a = 5, b = 5, c = 5;

// ✅ Same type, different values


int x = 10, y = 20, z = 30;

// ✅ Just declaration
int num1, num2, num3;

// Using them
[Link]($"x={x}, y={y}, z={z}");
// Output: x=10, y=20, z=30

Can't Mix Types:

csharp

// ❌ WRONG - Different types


int age, string name; // ERROR!

// ✅ CORRECT - Separate lines for different types


int age = 25;
string name = "Ali";

7. HOW DO YOU PRINT THE VALUE OF A VARIABLE TO THE CONSOLE?

Answer: Using [Link]()

csharp
// Method 1: Direct variable
int age = 25;
[Link](age);

// Method 2: With text


[Link]("Age: " + age);

// Method 3: String interpolation (Best!)


[Link]($"Age: {age}");

// Method 4: Placeholder
[Link]("Age: {0}", age);

// Multiple variables
string name = "Ali";
[Link]($"Name: {name}, Age: {age}");

8. WHAT DOES THE STATEMENT age *= 2; DO?

Answer: Multiplies age by 2 and stores the result back in age.

csharp

int age = 10;


[Link](age); // 10

age *= 2; // Same as: age = age * 2


[Link](age); // 20

age *= 2; // Multiply by 2 again


[Link](age); // 40

// Other shorthand operators:


int num = 100;
num += 10; // num = num + 10 → 110
num -= 5; // num = num - 5 → 105
num *= 2; // num = num * 2 → 210
num /= 3; // num = num / 3 → 70
num %= 8; // num = num % 8 → 6
EXERCISES SECTION

Exercise 1: Change Unit Speed

csharp

// Convert km/h to m/s


int speedKmh = 100; // 100 km/h
double speedMs = speedKmh / 3.6;
[Link]($"{speedKmh} km/h = {speedMs} m/s");

Exercise 2: Define Speed Variable

csharp

// Define a speed variable


int speed = 60; // km/h
[Link]($"Current speed: {speed} km/h");

Exercise 3: Double Variable

csharp

// Using double for decimal numbers


double temperature = 36.6;
double price = 99.99;
[Link]($"Temperature: {temperature}°C");
[Link]($"Price: ${price}");

Exercise 4: Fix Uninitialized Error

csharp

// ❌ WRONG
int count;
[Link](count); // ERROR!

// ✅ FIXED
int count = 0;
[Link](count); // 0
QUICK REFERENCE

Concept Example

Declare variable int age;

Initialize age = 25;

Declare + Initialize int age = 25;

Increment age++ or age += 1

Decrement age-- or age -= 1

Multiply age *= 2

Print [Link](age);

Multiple variables int a = 1, b = 2;

Notes prepared for: C# Variables Guide


Date: December 2025
Variables are the foundation - Master them! 🚀

You might also like