Chapter 10: Methods

1. What is a Method? (Super Simple Explanation)

A method is a named block of code that:

  • Does a specific job
  • Can take input (parameters)
  • Can give back output (return value)
  • Can be called (invoked) many times from different places

Syntax (basic):

C#

2. Basic Method – No Parameters, No Return

C#

3. Parameters – Sending Data Into Methods

Parameters are inputs the method needs to do its job.

A. Value Parameters (Most Common – Default)

C#

Important: When you pass a value type (int, double, bool, struct), it’s passed by value → a copy is made → changing it inside method doesn’t affect original.

C#

B. ref Parameter – Pass by Reference (Change Original Value)

C#

C. out Parameter – Method Must Assign a Value

C#

Common pattern: TryParse uses out

C#

D. params Parameter – Variable Number of Arguments

C#

4. Return Types – Getting Data Back from Methods

Methods can return any type (or nothing → void)

C#

Multiple returns? → Use out or return a class/tuple

5. Method Overloading – Same Name, Different Parameters

Same method name, different parameter list (number, type, or order)

C#

6. Optional / Default Parameters (Very Useful!)

You can give default values – caller can skip them

C#

Rule: Optional parameters must come after required ones.

7. Mini-Project: Smart Bank Account with Methods

C#

Quick Cheat Sheet – Methods

C#

Your Homework (Super Practical!)

  1. Create a new console project called MethodMaster
  2. Create a class Student with:
    • Properties: Name, RollNumber, Marks (array or List<double>)
    • Method: AddMark(double mark) – add a mark
    • Method: GetAverage() – return average (use params or List)
    • Method: PrintReport(string title = “Student Report”) – optional title
    • Overloaded AddMark for single mark or multiple (params)
  3. In Program.cs: Create a student, add 5 marks, print average and report

Next lesson: Access Modifiers & Encapsulation – we’re going to learn how to protect our data and make classes professional!

You’re doing absolutely fantastic! 🎉 Any part of methods confusing? Want more examples with ref, out, or overloading? Just tell me — I’m right here for you! 💙

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *