.NET ProgrammingUnit 210 min read
C Basics: Syntax, Data Types, Operators & Control Flow
Unit 2 of .NET Programming covers C fundamentals—variable declarations, data types, operators, control structures (if-else, loops), and basic I/O—with syntax rules, memory behavior, and real-world applications in .NET apps.
TAKEAWAYS
- C# is statically typed, requiring explicit variable declarations (e.g.,
int,string) and enforcing type safety at compile time. - Operators (arithmetic, logical, bitwise) and control flow (
if-else,switch,for,while) enable decision-making and iteration in programs. - Input/Output (
Console.ReadLine(),Console.WriteLine()) is the foundation for user interaction in console applications. - Memory management in C# relies on value types (stack-allocated) vs. reference types (heap-allocated), affecting performance and garbage collection.
- Common pitfalls: implicit conversions, off-by-one errors in loops, and incorrect operator precedence can lead to runtime errors.
- Real-world tie: C# powers Khalti’s transaction validation (data types for amounts), Daraz’s order processing (loops for inventory checks), and Ncell’s billing systems (control flow for plan selections).
1. C# Syntax and Structure
C# is a case-sensitive, compiled language that runs on the .NET Framework. Every executable program starts with a Main method, the entry point.
using System; // Required for basic I/O and other libraries
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, .NET!"); // Output to console
}
}
Key Rules:
- Naming conventions: Classes start with uppercase (
Program), methods with PascalCase (Main), variables with camelCase (userName). - Semicolons (
;) terminate statements. - Braces
{}enclose blocks of code (methods, loops, etc.).
2. Data Types in C#
C# supports primitive (built-in) and complex (user-defined) data types. They are categorized as:
- Value Types (stored directly in memory, stack-allocated):
- Numeric:
int,float,double,decimal,byte,short,long - Boolean:
bool(true/false) - Character:
char(16-bit Unicode) - Structs (e.g.,
DateTime,Point)
- Numeric:
- Reference Types (stored as pointers to heap memory):
- Classes (e.g.,
string,List<T>) - Arrays, delegates, interfaces
- Classes (e.g.,
| Category | Examples | Memory Location | Key Feature |
|---|---|---|---|
| Value Types | int, float, struct |
Stack | Copied when assigned |
| Reference Types | string, class, array |
Heap | Points to memory; shared across variables |
Example: Variable Declaration
int age = 25; // Value type (stack)
string name = "Alice"; // Reference type (heap)
double salary = 35000.50; // 64-bit floating-point
bool isEmployed = true; // Boolean flag
Visual: Memory Allocation
graph LR
A["Stack"] --> B["int age = 25\n(4 bytes)"]
A --> C["bool isEmployed = true\n(1 byte)"]
D["Heap"] --> E["string name = \"Alice\"\n(pointer to heap)"]
E --> F["Heap Memory\n\"Alice\" (object)"]Real-World Use:
- Khalti uses
decimalfor transaction amounts to avoid floating-point precision errors. - Ncell’s billing system stores customer IDs as
int(value type) for fast comparisons.
3. Operators in C#
Operators perform operations on variables and values. They are classified as:
| Category | Operators | Example | Associativity |
|---|---|---|---|
| Arithmetic | +, -, *, /, %, ++, -- |
int sum = a + b; |
Left-to-right |
| Relational | ==, !=, >, <, >=, <= |
if (x > 10) |
Left-to-right |
| Logical | && (AND), ` |
(OR),!` (NOT) |
|
| Bitwise | &, ` |
, ^, ~`, <<, >> |
int mask = x & 0xFF; |
| Assignment | =, +=, -=, *=, /= |
x += 5; |
Right-to-left |
Example: Operator Precedence
int result = 10 + 5 * 2; // Multiplication first → 10 + 10 = 20
Trace Table:
| Expression | Step-by-Step Evaluation | Final Value |
|---|---|---|
5 * 2 |
10 | 10 |
10 + 10 |
20 | 20 |
Real-World Use:
- Daraz’s discount calculator uses
*for percentage reductions:decimal finalPrice = originalPrice * (1 - discountPercentage);
4. Control Flow Statements
Control flow determines the order of execution. Key constructs:
A. Conditional Statements
if-elseint age = 20; if (age >= 18) { Console.WriteLine("Eligible to vote."); } else { Console.WriteLine("Too young to vote."); }Visual: Decision Tree
switch-case(for multiple conditions)char grade = 'B'; switch (grade) { case 'A': Console.WriteLine("Excellent"); break; case 'B': Console.WriteLine("Good"); break; default: Console.WriteLine("Invalid grade"); }
Real-World Use:
- NTC’s speed limit enforcement uses
if-elseto classify vehicles:if (speed > 60) Console.WriteLine("Over speed limit!");
B. Loops
forloop (known iterations)for (int i = 1; i <= 5; i++) { Console.WriteLine($"Iteration {i}"); }Trace Table:
Iteration iValueCondition i <= 5Action 1 1 True Print "Iteration 1" 2 2 True Print "Iteration 2" ... ... ... ... 5 5 True Print "Iteration 5" 6 6 False Exit loop whileloop (unknown iterations)int count = 0; while (count < 3) { Console.WriteLine($"Count: {count}"); count++; }do-whileloop (executes at least once)int num; do { Console.Write("Enter a positive number: "); num = Convert.ToInt32(Console.ReadLine()); } while (num <= 0);
Real-World Use:
- Pathao’s ride allocation uses a
whileloop to find the nearest available driver:while (driversAvailable.Count > 0 && !foundDriver) { // Check each driver's location }
5. Input and Output
C# uses Console class for basic I/O:
- Input:
Console.ReadLine()(returnsstring),Convert.ToInt32()(parses strings to numbers). - Output:
Console.WriteLine(),Console.Write().
Example: User Interaction
Console.Write("Enter your name: ");
string name = Console.ReadLine();
Console.WriteLine($"Hello, {name}!");
Trace:
| Step | Action | Output/Input |
|---|---|---|
| 1 | Console.Write("Enter your name: ") |
Prints prompt |
| 2 | name = Console.ReadLine() |
User types "Alice" |
| 3 | Console.WriteLine(...) |
Prints "Hello, Alice!" |
Real-World Use:
- eSewa’s login system uses
Console.ReadLine()to capture user credentials (in real apps, this is replaced with secure input methods).
6. Common Pitfalls and Best Practices
| Pitfall | Example | Fix |
|---|---|---|
| Implicit conversion | int x = 10.5; (error) |
Use double x = 10.5; or cast: (int)10.5 |
| Off-by-one error | for (int i = 0; i <= 10; i++) |
Adjust loop condition: i < 10 |
| Operator precedence | int result = 10 + 5 * 2 / 2; |
Use parentheses: 10 + (5 * 2) / 2 |
| Uninitialized variables | int y; Console.WriteLine(y); |
Initialize: int y = 0; |
In the Real World
Khalti’s Transaction System
- Idea Used: Data Types and Operators
- How: Transactions use
decimalto store amounts (e.g.,decimal amount = 500.75m;) to avoid floating-point rounding errors. Operators like+and-handle deductions and refunds. - Code Snippet:
decimal balance = 1000.50m; decimal deduction = 200.25m; balance -= deduction; // Updates balance to 800.25m
Daraz’s Order Processing
- Idea Used: Loops and Control Flow
- How: A
forloop iterates through inventory to check stock availability before confirming an order. - Example:
foreach (var item in order.Items) { if (warehouse.CheckStock(item.ProductId, item.Quantity)) { Console.WriteLine($"Processing {item.Name}..."); } else { Console.WriteLine($"Out of stock: {item.Name}"); } }
Ncell’s Billing Plan Selector
- Idea Used:
switch-casefor Menu-Driven Logic - How: Customers select plans (e.g., 'A', 'B', 'C') using a
switchstatement to apply different rates. - Example:
Console.Write("Select plan (A/B/C): "); char plan = Console.ReadLine()[0]; switch (plan) { case 'A': Console.WriteLine("1000 calls/month"); break; case 'B': Console.WriteLine("Unlimited calls"); break; default: Console.WriteLine("Invalid plan"); }
- Idea Used:
Exam Tip
- Syntax is Critical: Memorize keywords (
int,for,if,Console.WriteLine) and their exact usage. Partial credit is rare for syntax errors. - Trace Tables: For loops and conditions, always show initialization, condition check, and update steps in your answer.
- Data Type Questions: Expect questions on:
- When to use
intvs.double(e.g.,intfor counts,doublefor measurements). - The difference between value and reference types (e.g.,
intvs.string).
- When to use
- Operator Precedence: Always parenthesize expressions to avoid mistakes (e.g.,
(a + b) * cvs.a + b * c). - Real-World Scenarios: Relate control flow to systems like:
- Bank loan approval (
if-elsefor eligibility checks). - Traffic light system (
switch-casefor light changes).
- Bank loan approval (
- Common Exam Patterns:
- Debugging: Given a broken loop, identify the off-by-one error.
- Output Prediction: Trace a
forloop to predict console output. - Type Conversion: Convert between
stringand numeric types (e.g.,int.Parse()vs.Convert.ToInt32()).
Pro Tip: Practice writing small programs (e.g., a calculator, grade checker) to reinforce syntax and logic. Use Visual Studio or VS Code with the C# extension for real-time error checking.
Based on the TU BITM syllabus for .NET Programming (IT275), unit 2.
Discussion
Loading…