.NET ProgrammingUnit 212 min read

C Basics: Syntax, Data Types, Operators & Control Flow

Unit 2 of .NET Programming covers the foundational syntax of C, including variable declaration, data types, operators, control structures (if-else, loops), and basic input/output. This note explains how C differs from other languages, provides visual traces of code execution, and connects concepts to real-world applica

1. Introduction to C# Syntax

C# (pronounced "C sharp") is a statically typed, object-oriented programming language developed by Microsoft for the .NET framework. It is designed for readability, type safety, and performance, making it ideal for building Windows applications, web services, and enterprise software.

Key Features of C#

  • Case-sensitive: MyVar ≠ myvar
  • Compiled language: Code is converted to Intermediate Language (IL) before execution by the Common Language Runtime (CLR).
  • Strongly typed: Variables must be declared with a specific data type.
  • Garbage collection: Automatic memory management (no manual free() or delete like in C++).

Hello World in C#

using System;

class Program
{
    static void Main()
    {
        Console.WriteLine("Hello, World!"); // Output: Hello, World!
    }
}

Trace of Execution:

Step Action Output
1 using System; (imports library) (No output)
2 Main() starts execution (No output)
3 Console.WriteLine() executes Hello, World!

2. Data Types in C#

C# supports value types (stored directly in memory) and reference types (stored as pointers to memory locations).

A. Value Types (Stored on Stack)

Category Data Type Size (bytes) Range (Example) Example Usage
Integer int 4 to int age = 25;
long 8 to long population = 3000000000L;
short 2 to short year = 2024;
Floating float 4 ~6-7 decimal digits float pi = 3.14f;
double 8 ~15-16 decimal digits double salary = 50000.50;
Decimal decimal 16 28-29 decimal digits decimal price = 99.99m;
Boolean bool 1 true or false bool isLoggedIn = true;
Character char 2 Unicode (e.g., 'A', 'α') char grade = 'A';

B. Reference Types (Stored on Heap)

  • string: Immutable sequence of characters (e.g., "Hello").
  • object: Base class for all types (e.g., object x = 10;).
  • Arrays: Fixed-size collections (e.g., int[] numbers = {1, 2, 3};).
  • Classes/Structs: User-defined types (e.g., class Person { ... }).

Visual: Stack vs. Heap Memory

graph LR
    A["Stack Memory (Value Types)"] --> B["int x = 5;\n\nValue: 5"]
    C["Heap Memory (Reference Types)"] --> D["string name = \"Alice\";\n\nPointer to Heap:\n|----> \"Alice\""]
    A -->|"Call Stack"| E["Main()\nMethod1()\nMethod2()"]
    C -->|"Garbage Collection"| F["Unused objects\nare cleaned up"]

3. Variables and Constants

Variable Declaration

int age;          // Declaration
age = 25;         // Assignment
int age = 25;     // Declaration + Assignment

Rules:

  • Must start with a letter or _ (e.g., _count, totalPrice).
  • Cannot be a C# keyword (e.g., int class = 10; → Error).
  • Use PascalCase for types (int Age) and camelCase for variables (string firstName).

Constants

const double PI = 3.14159; // Immutable value

Use Case in Real World:

  • eSewa uses constants for fixed transaction fees (e.g., const decimal SERVICE_FEE = 1.50m;).

4. Operators in C#

Operators perform operations on variables and values.

-2-1123456-4-224681012xyx + 5x * 2x / 2x=2 → 7x=4 → 8
Arithmetic operators in action (y = f(x))

A. Arithmetic Operators

Operator Name Example Result
+ Addition 5 + 3 8
- Subtraction 10 - 4 6
* Multiplication 3 * 4 12
/ Division 10 / 3 3 (integer division)
% Modulus 10 % 3 1
++ Increment x++ x = x + 1
-- Decrement y-- y = y - 1

Example: Calculating Discount in Daraz

double originalPrice = 1000.00;
double discountRate = 0.20; // 20% off
double finalPrice = originalPrice - (originalPrice * discountRate);
Console.WriteLine($"Final Price: {finalPrice}"); // Output: 800

B. Relational Operators

Operator Name Example Result
== Equal to 5 == 5 true
!= Not equal to 5 != 3 true
> Greater than 10 > 5 true
< Less than 3 < 5 true
>= Greater/Equal 5 >= 5 true
<= Less/Equal 3 <= 5 true

C. Logical Operators

Operator Name Example Result
&& AND true && false false
|| OR true || false true
! NOT !true false
^ XOR true ^ false true

Example: Pathao’s Ride Matching Logic

bool hasDriver = true;
bool hasPassenger = true;
bool isWeatherGood = true;

if (hasDriver && hasPassenger && isWeatherGood)
{
    Console.WriteLine("Ride matched successfully!");
}
else
{
    Console.WriteLine("Ride matching failed.");
}

5. Control Structures

startTrueFalseStartCondition CheckIf-BlockElse-BlockEnd
State diagram of an `if-else` conditional

A. Conditional Statements (if-else)

Example: NTC Electricity Bill Calculation

int unitsConsumed = 300;
double bill = 0;

if (unitsConsumed <= 100)
{
    bill = unitsConsumed * 1.50;
}
else if (unitsConsumed <= 300)
{
    bill = 100 * 1.50 + (unitsConsumed - 100) * 2.00;
}
else
{
    bill = 100 * 1.50 + 200 * 2.00 + (unitsConsumed - 300) * 3.00;
}

Console.WriteLine($"Total Bill: {bill}"); // Output: 500

B. Loops

1. for Loop

for (int i = 1; i <= 5; i++)
{
    Console.WriteLine($"Iteration {i}");
}

Output:

Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5

2. while Loop

int count = 1;
while (count <= 3)
{
    Console.WriteLine($"Count: {count}");
    count++;
}

Output:

Count: 1
Count: 2
Count: 3

3. do-while Loop

int num = 1;
do
{
    Console.WriteLine($"Number: {num}");
    num++;
} while (num <= 3);

Output (same as while):

Number: 1
Number: 2
Number: 3

Example: NEPSE Stock Price Checker

string userInput;
do
{
    Console.Write("Enter stock symbol (or 'quit' to exit): ");
    userInput = Console.ReadLine();
    if (userInput.ToLower() != "quit")
    {
        Console.WriteLine($"Fetching data for {userInput}...");
        // Simulate API call
    }
} while (userInput.ToLower() != "quit");

6. Input and Output

A. Console.ReadLine()

Console.Write("Enter your name: ");
string name = Console.ReadLine();
Console.WriteLine($"Hello, {name}!");

B. Console.ReadKey()

Console.Write("Press any key to continue...");
Console.ReadKey(); // Waits for user input

C. Formatted Output (string.Format or $ Interpolation)

string name = "Alice";
int age = 25;
Console.WriteLine($"User: {name}, Age: {age}"); // Output: User: Alice, Age: 25

7. Type Conversion

A. Implicit Conversion (Safe)

int a = 10;
double b = a; // int → double (safe)
Console.WriteLine(b); // Output: 10

B. Explicit Conversion (Requires Casting)

double x = 9.78;
int y = (int)x; // double → int (truncates decimal)
Console.WriteLine(y); // Output: 9

C. Convert and Parse Methods

string numStr = "123";
int num = Convert.ToInt32(numStr); // "123" → 123
int num2 = int.Parse("456");       // "456" → 456

Example: Khalti Payment Validation

string amountStr = "500";
try
{
    decimal amount = Convert.ToDecimal(amountStr);
    Console.WriteLine($"Processing payment of: {amount}");
}
catch (FormatException)
{
    Console.WriteLine("Invalid amount format!");
}

8. Arrays in C#

Arrays store multiple values of the same type in a contiguous memory block.

Declaration and Initialization

int[] numbers = new int[5]; // Size 5, uninitialized
numbers[0] = 10;
numbers[1] = 20;

int[] primes = { 2, 3, 5, 7 }; // Initialized directly

Accessing Array Elements

Console.WriteLine(primes[2]); // Output: 5

Looping Through an Array

foreach (int prime in primes)
{
    Console.WriteLine(prime);
}

Output:

2
3
5
7

Visual: Array Memory Layout

20315273primes[0] = 2primes[1] = 3primes[2] = 5primes[3] = 7
Memory layout of `int[] primes = {2, 3, 5, 7};` (addresses are illustrative)

Example: Daraz Order Queue

string[] orderQueue = new string[5];
orderQueue[0] = "Order123";
orderQueue[1] = "Order456";

Console.WriteLine($"Processing order: {orderQueue[0]}");

In the Real World

  1. eSewa Transaction Validation

    • Concept Used: if-else conditions and type conversion.
    • How? When you pay via eSewa, the app checks:
      if (Convert.ToDecimal(amount) > 0 && isConnectedToInternet)
      {
          ProcessPayment();
      }
      else
      {
          ShowError("Invalid amount or no internet!");
      }
      
  2. Pathao Ride Matching

    • Concept Used: Logical operators (&&) and loops.
    • How? The app matches drivers and passengers only if:
      • Both are online (driverOnline && passengerOnline).
      • The ride request is within the driver’s availability zone (checked in a loop).
  3. NTC Electricity Bill Calculation

    • Concept Used: Nested if-else for tiered pricing.
    • How? Bills are calculated differently based on usage:
      if (units <= 100) { bill = units * 1.50; }
      else if (units <= 300) { bill = 100*1.50 + (units-100)*2.00; }
      
  4. Khalti Payment Retry Logic

    • Concept Used: do-while loop for retries.
    • How? If a payment fails, Khalti retries up to 3 times:
      int retryCount = 0;
      do
      {
          if (ProcessPayment()) break;
          retryCount++;
      } while (retryCount < 3);
      
  5. NEPSE Stock Price Alerts

    • Concept Used: Arrays to store stock symbols and loops to check prices.
    • How? A trader’s app might track multiple stocks:
      string[] watchedStocks = { "NTC", "NMB", "HBANK" };
      foreach (string stock in watchedStocks)
      {
          double price = FetchStockPrice(stock);
          if (price > threshold) AlertUser(stock);
      }
      

Exam Tip

  1. Syntax is Critical: C# is strict about semicolons (;), braces ({}), and case sensitivity. Always double-check.
  2. Trace Execution: For loop questions, draw a table showing variable changes (like the Hello World trace above).
  3. Common Pitfalls:
    • Forgetting to initialize variables (e.g., int x; → Error if used uninitialized).
    • Confusing == (comparison) with = (assignment).
    • Off-by-one errors in loops (e.g., for (int i = 0; i <= 5; i++) runs 6 times).
  4. Real-World Scenarios: Expect questions like:
    • "How would you validate a Khalti payment amount using if-else?"
    • "Write a loop to process orders in a Daraz queue."
  5. Code Structure: Always include:
    • using System; at the top.
    • A Main() method for executable code.
    • Proper indentation for readability.

Practice Questions

  1. Write a C# program to check if a number is even or odd using a ternary operator.
  2. Declare an array of 5 integers, initialize it with values, and print the sum of all elements.
  3. Explain the difference between == and .Equals() in C#.
  4. How would you use a do-while loop to keep asking for user input until a valid number is entered?
  5. Trace the output of the following code:
    int x = 5;
    int y = x++ + ++x;
    Console.WriteLine(y); // What is the output?
    

Based on the TU BIM syllabus for .NET Programming (IT275), unit 2.

Discussion

Loading…