C# ยท Chapter 25 of 46

C# Methods

A method is a reusable block of code that performs a specific task, defined once and called whenever needed. Methods help organize code, avoid repetition, and make programs easier to understand.

A method has a name, a return type (or void if it returns nothing), and optionally, parameters that let you pass values into it.

Syntax
static returnType MethodName(parameters) {
  // code
  return value;
}

Defining and calling methods

A method is declared with an access modifier, return type, name, and parentheses, like `static int Add(int a, int b)`. It's called by using its name followed by arguments in parentheses.

Return values

A method with a non-void return type must use the `return` keyword to send a value back to the caller. void methods perform an action but don't return a value.

Example 1 (csharp)
using System;

class Program {
  static int Add(int a, int b) {
    return a + b;
  }

  static void Main() {
    int result = Add(3, 4);
    Console.WriteLine(result);
  }
}
Output
7

Add() takes two ints, returns their sum, and Main() prints the result.

Example 2 (csharp)
using System;

class Program {
  static void Greet(string name) {
    Console.WriteLine("Hello, " + name);
  }

  static void Main() {
    Greet("Amy");
  }
}
Output
Hello, Amy

Greet() is a void method that performs an action without returning a value.

Key points

  • Methods make code reusable and organized.
  • A method's return type must match the type of the value it returns.
  • void methods perform actions without returning a value.
  • Methods are called by their name followed by parentheses with any arguments.
๐Ÿ’ก Note: Breaking a program into small, well-named methods makes it much easier to test and debug.

๐Ÿ“ Quick Quiz

1. What keyword sends a value back from a method?

2. What return type is used when a method returns nothing?

3. Why are methods useful?