← C# EnglishChapter 05 of 13

Methods

## Learning Objectives - Define and call methods - Understand parameters and return values - Master method overloading - Learn out and ref parameters - Understand optional parameters ## Defining Methods ### Basic Structure ```csharp static void Greet() { Console.WriteLine("Hello!"); } ``` ### Method with Return Type ```csharp static int Add(int a, int b) { return a + b; } ``` ### Calling Methods ```csharp class Program { static void Main() { Greet(); // void method int sum = Add(5, 3); // returns 8 Console.WriteLine(sum); } static void Greet() { Console.WriteLine("Hello!"); } static int Add(int a, int b) { return a + b; } } ``` ## Parameters and Arguments ### Passing Arguments ```csharp static void PrintName(string name) { Console.WriteLine("Name: " + name); } // Call with argument PrintName("Alice"); ``` ### Multiple Parameters ```csharp static int CalculateArea(int width, int height) { return width * height; } int area = CalculateArea(5, 10); // 50 ``` ### Return Values ```csharp static bool IsEven(int number) { return number % 2 == 0; } if (IsEven(4)) { Console.WriteLine("Even"); } ``` ## Return Types ### void (No Return) ```csharp static void PrintHello() { Console.WriteLine("Hello"); } ``` ### Return Early ```csharp static string GetGrade(int score) { if (score >= 90) return "A"; if (score >= 80) return "B"; if (score >= 70) return "C"; return "F"; } ``` ### Multiple Returns (Guard Clauses) ```csharp static bool Validate(int age, string name) { if (age < 0) return false; if (string.IsNullOrEmpty(name)) return false; // main validation return true; } ``` ## Method Overloading ### Same Name, Different Parameters ```csharp static int Add(int a, int b) { return a + b; } static double Add(double a, double b) { return a + b; } static int Add(int a, int b, int c) { return a + b + c; } ``` ### How It Works ```csharp Add(5, 3); // Calls Add(int, int) Add(5.0, 3.0); // Calls Add(double, double) Add(1, 2, 3); // Calls Add(int, int, int) ``` ### Overload Resolution C# determines which method to call based on: 1. Number of arguments 2. Type of arguments 3. Order of argument types ## Optional Parameters ### Default Values ```csharp static void PrintMessage(string message, string prefix = "Info:") { Console.WriteLine($"{prefix} {message}"); } PrintMessage("Hello"); // Info: Hello PrintMessage("Hello", "Warning:"); // Warning: Hello ``` ### Optional Must Come Last ```csharp // Valid static void Example(int required, string optional = "default") { } // Invalid // static void Example(string optional = "default", int required) { } ``` ## Named Arguments ### Call by Name ```csharp static void PrintOrder(string product, int quantity, double price) { Console.WriteLine($"{product}: {quantity} x {price}"); } PrintOrder(product: "Widget", quantity: 5, price: 9.99); PrintOrder(price: 9.99, product: "Widget", quantity: 5); ``` ## out Parameter ### Return Multiple Values ```csharp static bool TryParse(string input, out int result) { try { result = int.Parse(input); return true; } catch { result = 0; return false; } } // Usage if (TryParse("123", out int number)) { Console.WriteLine("Parsed: " + number); } ``` ### Discarding out (C# 7+) ```csharp if (int.TryParse("123", out _)) { Console.WriteLine("Valid number"); } ``` ## ref Parameter ### Pass by Reference ```csharp static void DoubleIt(ref int x) { x = x * 2; } int num = 5; DoubleIt(ref num); Console.WriteLine(num); // 10 ``` ### ref vs out | ref | out | |-----|-----| | Must be initialized before passing | Must be assigned inside method | | Can read or write | Must write before returning | ## params Parameter ### Variable Arguments ```csharp static int Sum(params int[] numbers) { int total = 0; foreach (int num in numbers) { total += num; } return total; } // Can pass any number of arguments Sum(1, 2, 3); // 6 Sum(1, 2, 3, 4, 5); // 15 Sum(); // 0 ``` ### With Regular Parameters ```csharp static void PrintAll(string prefix, params int[] numbers) { foreach (int num in numbers) { Console.WriteLine($"{prefix} {num}"); } } PrintAll("Value:", 1, 2, 3); ``` ## Static vs Instance Methods ### Static Methods Belong to class, not instance: ```csharp static class MathUtils { public static int Square(int x) { return x * x; } } // Call without creating instance int result = MathUtils.Square(5); ``` ### When to Use static - Utility methods (Math.Random(), Console.WriteLine()) - Methods that don't need instance data - Constants ### Instance Methods Require object instance: ```csharp class Person { private string _name; public void SetName(string name) { _name = name; } public string GetName() { return _name; } } // Must create instance Person p = new Person(); p.SetName("Alice"); Console.WriteLine(p.GetName()); ``` ## Passing Primitives vs References ### Primitives (Pass by Value) ```csharp static void DoubleIt(int x) { x = x * 2; // Only affects local copy } int num = 5; DoubleIt(num); Console.WriteLine(num); // Still 5 ``` ### Reference Types (Pass by Reference) ```csharp static void ChangeName(Person p) { p.SetName("Bob"); // Affects original object } static void Reassign(Person p) { p = new Person(); // Only affects local copy p.SetName("Charlie"); } Person person = new Person(); person.SetName("Alice"); ChangeName(person); Console.WriteLine(person.GetName()); // Bob ``` ## Recursion ### Method Calling Itself ```csharp static int Factorial(int n) { if (n <= 1) return 1; return n * Factorial(n - 1); } // factorial(5) = 5 * 4 * 3 * 2 * 1 = 120 ``` ### Iterative Alternative ```csharp static int Factorial(int n) { int result = 1; for (int i = 2; i <= n; i++) { result *= i; } return result; } ``` ## Local Functions (C# 7+) ### Nested Methods ```csharp static int Calculate(params int[] numbers) { int Sum() { int total = 0; foreach (int n in numbers) total += n; return total; } int Count() => numbers.Length; return Sum() / Count(); } ``` ## Summary - Methods: `access_modifier static? return_type name(params) { }` - Overloading: same name, different parameters - Optional: `type name = default` for optional params - Named arguments: `method(param: value)` - out: returns additional value (must assign inside) - ref: passes by reference (must initialize before) - params: `params type[]` for variable arguments - static: belongs to class - Recursion: method calls itself (ensure base case)

Comments

Comments powered by Giscus

To enable comments, add your Giscus embed code here.

Learn more about Giscus →