CodeGym /Courses /C# SELF /Intro to Functions (Methods) in C#

Intro to Functions (Methods) in C#

C# SELF
Level 8, Lesson 2
Available

1. Functions/Methods in C#

You've already learned a bunch of commands in C#, so you can write pretty complex programs. 10, 20, 30 lines of code in a program — that's not really a big program, right?

But a program with 100+ lines — that's already big, and it's kinda hard to figure out what's going on in the code. Is there a way to make writing and reading big programs easier?

Yep, and that's where methods (functions) come in.

So, what is a method? To put it super simply, a method is a group of commands that has a unique name. In other words, we just bundle a few commands together and give that group a unique name. That's it — now you have a method.

Let's say you have some code to draw a cat:

Console.WriteLine("  |\\__/,|   (`\\");
Console.WriteLine("  |o_o  |__ _) )");
Console.WriteLine("  (____/   (_/ ");
Code to draw a cat

Here's what it prints:

  |\__/,|   (`\
  |o_o  |__ _) )
  (____/   (_/

You can just move this into a separate method and draw as many cats as you want:

void WriteCat()
{
    Console.WriteLine("  |\\__/,|   (`\\");
    Console.WriteLine("  |o_o  |__ _) )");
    Console.WriteLine("  (____/   (_/ ");    
}

//draw three cats
WriteCat();
WriteCat();
WriteCat();
Using a method to print the cat multiple times

When the program runs, every time you call WriteCat() it will execute all the commands inside the WriteCat() method. We just made a new command (method) by grouping a few commands together.

Why functions are awesome:

  • They split your program into parts, each doing its own thing.
  • Make it easy to reuse code: write it once, use it as many times as you want.
  • Lower the chance of bugs: if there's a bug in a function, you fix it in one place.
  • Give your code "names" for complex actions — makes it way more readable.

Terminology: function, method, procedure

In C#, the terms function and method usually mean the same thing, but there are some small differences.

  • Method — a function that belongs to a class or object (in C#, almost everything is a method).
  • Procedure — a function that doesn't return a value (void methods).
  • Function — in a broad sense, any named part of a program you can call.

Officially in C#, all of these are called methods, but if you see "function" somewhere later — don't freak out!

2. Method declaration syntax: breaking it down

Let's break down a super simple function, the classic "Hello, World!", but we'll move the print into a separate method:

using System;

class Program
{
    static void Main()
    {
        PrintHello();
    }

    static void PrintHello()	// print Hello, World! text
    {
        Console.WriteLine("Hello, World!");
    }
}
Example of declaring and calling a method

Syntax breakdown:

Part Example Description
Modifier
static
Shows the method belongs to the class (more on this later)
Return type
void
Means the method doesn't return anything
Method name
PrintHello
The name you use to call the method
Parameters
()
Arguments (empty — no arguments)
Method body
{ ... }
The code that runs when you call the method

Analogy:
You can think of a method like a coffee machine: you put in money (arguments), press a button (call the method), the machine makes coffee (method body), and gives you a result (return value) — or doesn't, if it's a void method!

3. How to call methods

Calling a method is just its name and parentheses, that's it:

PrintHello(); // Method with no parameters

int sum = Add(2, 3); // Method with parameters and a result

Important: you can only call a method after it's been declared (or if it's "above" in the code, or in the same class).

4. Methods with parameters

You can pass parameters to a method. This makes the method flexible and customizable for all sorts of situations. Basically, parameters are variables for the method, and you give them values when you call the method. You need to specify parameters when you create the method.

static void Greet(string name)
{
    Console.WriteLine($"Hello, {name}!");
}

// Usage:
Greet("Alice");
Greet("Bob");
Method with a parameter

Parameters — these are variables whose values you pass to the method when you call it.

Part Example Description
Parameter type
string
The type of value it takes
Parameter name
name
The name you use inside the method

Calls:
Greet("Alice"); — name gets the value "Alice".

Multiple parameters

You can declare several parameters separated by commas:

static void PrintSum(int a, int b)
{
    Console.WriteLine($"Sum: {a + b}");
}

// Usage:
PrintSum(5, 7); // Sum: 12
Method with multiple parameters

5. Value parameters and reference parameters

Function parameters are just regular variables, and the same rules apply to them as to other variables.

So remember: when you pass an array to a method, you're passing a reference to the array, so the method can change the contents of the array. For simple types (int, double), the value is copied.

static void ZeroFirstGrade(int[] grades)
{
    grades[0] = 0; // Changes the original array!
}

// Usage:
int[] a = {1, 2, 3, 4, 5};
ZeroFirstGrade(a);
Console.WriteLine(a[0]);	//prints 0
Passing an array by reference — the method changes the original data

Here's what's actually happening:

static void ZeroFirstGrade(int[] grades)
{
    grades[0] = 0; // Changes the original array!
}

// Usage:
int[] a = {1, 2, 3, 4, 5};

//ZeroFirstGrade(a);
int[] grades = a;
grades[0] = 0;

Console.WriteLine(a[0]);	//prints 0
Analogy for passing an array by reference
2
Task
C# SELF, level 8, lesson 2
Locked
Creating a method without parameters
Creating a method without parameters
2
Task
C# SELF, level 8, lesson 2
Locked
Creating a Method with a Parameter
Creating a Method with a Parameter
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION