Module 4: Modular Programming (Methods)
Student: Techritoma Interns
Time Allocation:
Goal: Organize code into reusable blocks, understand the Call Stack, and master recursion.
Part 1: The "DRY" Principle
DRY = Don't Repeat Yourself.
If you copy-paste code, you create a "maintenance debt." If you find a bug in one copy, you have to fix it
everywhere. Methods (called functions in other languages) solve this by encapsulating logic into a single,
callable unit.
Part 2: Anatomy of a Method
In C#, methods live inside classes. Since we aren't instantiating objects yet, we use static.
// [Modifiers] [Return Type] [Method Name] ([Parameters])
static int AddNumbers (int a, int b)
{
// The Body
int result = a + b;
return result; // Must match Return Type
}
Key Components:
1. Return Type: What does the method give back?
○ int, string, bool: The method must use the return keyword.
○ void: The method performs an action (like printing) and returns nothing.
2. Parameters: The inputs the method needs (variables defined in the parentheses).
3. Arguments: The actual values you pass in when calling the method.
Part 3: The CS Concept – The Call Stack
When your code runs, it doesn't just "jump" around. It uses a Stack data structure in memory.
1. Main() starts: A "Stack Frame" is created for Main. It holds Main's local variables.
2. Call Method A(): Execution pauses in Main. A new Stack Frame is pushed on top for Method A.
3. Return: When Method A finishes, its frame is popped (destroyed), and execution resumes in Main
exactly where it left off.
Visualizing Recursion (Method calling itself):
Calculates Factorial (5! = 5 * 4 * 3 * 2 * 1)
static int Factorial(int n)
{
// Base Case: Stop the recursion!
if (n == 1) return 1;
// Recursive Step
return n * Factorial(n - 1);
}
If you forget the Base Case, the stack frames pile up until memory runs out -> StackOverflowException.
Part 4: Advanced Features
1. Method Overloading
You can have multiple methods with the same name if they have different parameters.
static void Print(string message)
{
[Link]($"Message: {message}");
}
static void Print(int number)
{
[Link]($"Number: {number}");
}
// Usage:
Print("Hello"); // Calls the string version
Print(100); // Calls the int version
2. Optional Parameters
Assign a default value to make a parameter optional.
static void LogError(string error, bool isCritical = false)
{
string prefix = isCritical ? "[CRITICAL]" : "[INFO]";
[Link]($"{prefix} {error}");
}
// Usage:
LogError("File missing"); // isCritical is false
LogError("System Failure", true); // isCritical is true
Part 5: Practical Exercises
Exercise 1: The Geometry Helper
Create a class with the following static methods:
1. CalculateCircleArea(double radius) -> Returns area ( ).
2. CalculateRectangleArea(double width, double height) -> Returns area.
3. CalculateTriangleArea(double base, double height) -> Returns area.
Tip: Use [Link] for Pi.
Exercise 2: The Refactor (Cleanup)
Take your Calculator code from Module 3 and refactor it.
● Move the addition logic to a method Add(double a, double b).
● Move subtraction to Subtract(...), etc.
● Your Main method should now look clean, just calling these methods inside the switch statement.
Exercise 3: The Palindrome Checker
Write a method bool IsPalindrome(string text) that returns true if the text is the same forwards and
backwards (e.g., "racecar", "madam").
● Hint: You might need to reverse the string or use a loop to compare characters.
Checkpoint: Conceptual Quiz
1. Stack Trace: If Main calls MethodA, and MethodA calls MethodB, which stack frame is at the very
top?
2. Scope: If I declare int x = 5 inside MethodA, can I access x inside MethodB? Why or why not?
3. Code Fix: Why is this invalid?
static void GetNumber()
{
return 10;
}