Lesson 25 +10 XP

C# Methods

C# Methods

A method is a block of code that runs only when it's called. You can pass data into it and get data back.

Creating a method

A method is declared inside a class. It has a return type, a name, and parentheses:

static void MyMethod()
{
  Console.WriteLine("I just got executed!");
}

Calling a method

Call it by name followed by parentheses:

static void MyMethod()
{
  Console.WriteLine("I just got executed!");
}

static void Main(string[] args)
{
  MyMethod();
  MyMethod();
  MyMethod();
}

The output is:

I just got executed!
I just got executed!
I just got executed!

A method can be called many times - that's the whole point of code reuse.

The parts of a method

  • static - belongs to the class itself, callable without creating an object.
  • void - the return type; void means "returns nothing".
  • MyMethod - the method name.
  • () - where parameters go.

Why use methods?

  • Reuse code instead of copying it.
  • Break big problems into small, readable pieces.
  • Fix a bug in one place instead of everywhere.

TL;DR

  • Methods are reusable blocks of code.
  • static void MethodName() is the basic form.
  • void means it returns nothing.
  • Call a method with its name and ().