Methods

    Lesson 6 โ€ข Intermediate Track

    What You'll Learn

    • Define methods with parameters and return values (void, int, string, etc.)
    • Use expression-bodied members (=>) for concise one-liner methods
    • Work with optional parameters, named arguments, and params arrays
    • Return multiple values using out parameters
    • Understand method overloading โ€” same name, different parameter signatures
    • Write recursive methods (factorial, Fibonacci) with base cases

    ๐Ÿ’ก Real-World Analogy

    Methods are like kitchen appliances. A blender (method) takes ingredients (parameters), processes them, and gives you a smoothie (return value). A toaster takes bread, toasts it, and returns toast โ€” you don't need to know how the heating element works inside (abstraction). Overloading is like a multi-function cooker: same appliance name, but it bakes, steams, or pressure-cooks depending on what settings (parameters) you give it.

    ๐Ÿ“Š Method Syntax Quick Reference

    FeatureSyntaxExample
    Void methodstatic void Name()No return value
    Return valuestatic int Name()Must use return
    Expression bodystatic int Name() => expr;One-liner shorthand
    Optional paramvoid F(int x = 5)Default value if omitted
    Params arrayvoid F(params int[] nums)Variable argument count
    Out parameterbool F(out int result)Return multiple values
    Named argsF(name: "Bob", age: 25)Specify by name

    1. Defining & Calling Methods

    A method has a return type, name, and parameters. Use void when it doesn't return a value, or a type like int, string, double when it does. Expression-bodied methods (=>) are perfect for simple one-liners.

    Basic Methods

    Create void methods, return values, and expression-bodied methods.

    Try it Yourself ยป
    C#
    using System;
    
    class Program
    {
        // Void method โ€” no return value
        static void Greet(string name)
        {
            Console.WriteLine($"Hello, {name}! ๐Ÿ‘‹");
        }
    
        // Method with return value
        static int Add(int a, int b)
        {
            return a + b;
        }
    
        // Expression-bodied method (one-liner)
        static double CircleArea(double radius) => Math.PI * radius * radius;
    
        // Method with multiple returns
        static string GetGrade(int score)
        {
            if (score >= 90) return "A";
    ...

    2. Parameters โ€” Optional, Named, Params & Out

    Optional parameters have default values. Named arguments let you specify parameters in any order. params accepts a variable number of arguments. out lets a method return multiple values โ€” used heavily in TryParse patterns.

    Advanced Parameters

    Use optional params, named args, params arrays, and out parameters.

    Try it Yourself ยป
    C#
    using System;
    
    class Program
    {
        // Optional parameters (must be last)
        static void PrintMessage(string msg, int times = 1, string prefix = "โ†’")
        {
            for (int i = 0; i < times; i++)
                Console.WriteLine($"{prefix} {msg}");
        }
    
        // Params keyword โ€” variable number of arguments
        static int Sum(params int[] numbers)
        {
            int total = 0;
            foreach (int n in numbers)
                total += n;
            return total;
        }
    
        // Out parameter โ€” return multip
    ...

    3. Overloading & Recursion

    Method overloading means multiple methods with the same name but different parameter types or counts โ€” the compiler picks the right one. Recursion is when a method calls itself; it must have a base case to stop, or it causes a stack overflow.

    Overloading & Recursion

    Overload methods by signature and write recursive algorithms.

    Try it Yourself ยป
    C#
    using System;
    
    class Program
    {
        // Method overloading โ€” same name, different parameters
        static int Multiply(int a, int b) => a * b;
        static double Multiply(double a, double b) => a * b;
        static int Multiply(int a, int b, int c) => a * b * c;
    
        // Practical: formatting helper
        static string Format(int number) => number.ToString("N0");
        static string Format(double number) => number.ToString("F2");
        static string Format(decimal money) => money.ToString("C");
    
        // Recursi
    ...

    Pro Tips

    • ๐Ÿ’ก Keep methods short: A good method does one thing. If it's over 20 lines, consider splitting it.
    • ๐Ÿ’ก Use tuples instead of out for simple cases: static (int min, int max) GetRange(int[] arr) is often cleaner than out parameters.
    • ๐Ÿ’ก Prefer expression-bodied syntax for simple methods: static bool IsEven(int n) => n % 2 == 0; is clean and readable.
    • ๐Ÿ’ก Avoid deep recursion: C# has a limited stack size (~1MB). For large inputs, convert recursion to iteration or use tail-call patterns.

    Common Mistakes

    • Forgetting return: A method declared as static int Add() must use return in every code path. The compiler will catch this.
    • Optional params not last: void F(int x = 5, string name) won't compile โ€” optional parameters must come after required ones.
    • Return type mismatch: static int GetName() returning a string will cause a compile error. Match the return type to what you actually return.
    • Missing base case in recursion: Factorial(n) without if (n <= 1) return 1; recurses forever and crashes with StackOverflowException.
    • Overloading by return type only: C# doesn't allow two methods with the same name and parameters but different return types. Parameters must differ.

    ๐ŸŽ‰ Lesson Complete

    • โœ… Methods organise code into reusable blocks with parameters and return values
    • โœ… void methods perform actions; typed methods return values with return
    • โœ… Expression-bodied syntax (=>) for concise one-liner methods
    • โœ… Optional parameters, named arguments, params arrays, and out parameters
    • โœ… Method overloading: same name, different parameter signatures
    • โœ… Recursion: a method that calls itself with a base case to stop
    • โœ… Next lesson: Object-Oriented Programming โ€” classes, objects, and encapsulation

    Sign up for free to track which lessons you've completed and get learning reminders.

    Previous

    Cookie & Privacy Settings

    We use cookies to improve your experience, analyze traffic, and show personalized ads. You can manage your preferences below.

    By clicking "Accept All", you consent to our use of cookies for analytics and personalized advertising. You can customize your preferences or reject non-essential cookies.

    Privacy Policy โ€ข Terms of Service