Labs ICT
โญ Pro Login

Methods Introduction

A method is a named block of code that does something. You've already been using one โ€” Main. Now let's write your own.

Defining a Method

A method has a return type, a name, parentheses for parameters, and a body. If it doesn't return anything, use void.


using System;

class Program {
  static void SayHello() {
    Console.WriteLine("Hello!");
  }
  
  static void Main() {
    SayHello();
    SayHello();
  }
}
    
Try it Yourself โ†’

Return Types

Use return to send a value back to the caller. The method's return type must match what you return.


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);
  }
}
    
Try it Yourself โ†’

The static Keyword

static means the method belongs to the class itself, not to an instance. Since Main is static, any method it calls directly must also be static.


using System;

class Program {
  static int Square(int x) {
    return x * x;
  }
  
  static void Main() {
    Console.WriteLine(Square(5));
    Console.WriteLine(Square(12));
  }
}
    
Try it Yourself โ†’

Early Return

You can exit a method early with return. Useful for guard clauses โ€” check for invalid input at the top and bail out.


using System;

class Program {
  static string CheckAge(int age) {
    if (age < 0) return "Invalid";
    if (age >= 18) return "Adult";
    return "Minor";
  }
  
  static void Main() {
    Console.WriteLine(CheckAge(20));
    Console.WriteLine(CheckAge(-5));
  }
}
    
Try it Yourself โ†’

๐Ÿงช Quick Quiz

What keyword defines a method that belongs to the class itself, not an instance?