Tutorials / C# for Beginners / Writing your own methods

Writing your own methods

13 min read csharp
Course contents (16 lessons)
  1. Getting started
  2. Installing the .NET 10 SDK and checking it works
  3. Your first console app and top-level statements
  4. The building blocks
  5. Variables and basic types
  6. Working with strings and interpolation
  7. Reading input and writing output
  8. Making decisions and repeating work
  9. Conditionals and switch expressions
  10. Loops: for, while, do and foreach
  11. Collections and methods
  12. Arrays and List of T
  13. Writing your own methods
  14. Objects and classes
  15. Classes and objects
  16. Properties, encapsulation and object initialisers
  17. Handling null safely
  18. Errors and files
  19. Exceptions: try, catch, finally and throw
  20. Reading and writing files
  21. Final project: expense tracker
  22. Expense tracker, part 1: planning, model and storage
  23. Expense tracker, part 2: the menu and summaries

Why methods exist

When a program grows, one long list of statements becomes painful. You scroll to find things, and you copy the same lines in several places. A method is a named block of code that you can call whenever you need it. Write it once, use it many times, and fix bugs in one place.

You have already called methods: Console.WriteLine, Trim, Add. Now you write your own.

Declaring a method

A method has a return type, a name, a parameter list and a body. If it returns nothing, the return type is void.

decimal total = CalculateTotal(3, 49.99m);
Console.WriteLine($"Total with tax: {total:N2}");

PrintGreeting("Ayesha");
PrintGreeting("Bilal", excited: true);

Console.WriteLine(IsEven(10));
Console.WriteLine(IsEven(7));

var (min, max) = FindRange(new[] { 4, 9, 2, 7 });
Console.WriteLine($"Min {min}, max {max}");

Console.WriteLine(Factorial(5));

// Methods in top-level programs go below the statements
static decimal CalculateTotal(int quantity, decimal unitPrice, decimal taxRate = 0.17m)
{
    decimal subtotal = quantity * unitPrice;
    return subtotal + subtotal * taxRate;
}

static void PrintGreeting(string name, bool excited = false)
{
    string ending = excited ? "!" : ".";
    Console.WriteLine($"Hello, {name}{ending}");
}

static bool IsEven(int number) => number % 2 == 0;

static (int Min, int Max) FindRange(int[] numbers)
{
    int min = numbers[0];
    int max = numbers[0];
    foreach (int n in numbers)
    {
        if (n < min) min = n;
        if (n > max) max = n;
    }
    return (min, max);
}

static long Factorial(int n)
{
    if (n <= 1) return 1;
    return n * Factorial(n - 1);
}

Walking through it

CalculateTotal takes three parameters and returns a decimal. The third parameter has a default value, so callers may leave it out. A parameter with a default must come after the ones without. The return keyword sends the result back and ends the method.

PrintGreeting returns nothing. In the second call, I wrote excited: true. That is a named argument. It makes the call readable, because a bare true in a call tells you nothing. I use named arguments for any boolean.

IsEven uses the expression-bodied form. When a method is one expression, => replaces the braces and the return. A method that answers a yes-or-no question should return bool and be named like a question: IsEven, HasItems, CanLogin.

FindRange returns two values at once using a tuple. The caller unpacks them into two variables with var (min, max). Tuples are handy for small, local needs. If you return the same pair in many places, use a class instead.

Factorial calls itself. This is recursion. Each call solves a slightly smaller problem until it reaches the base case, n <= 1. Without the base case the method would call itself until the program crashed with a stack overflow.

Scope

A variable declared inside a method exists only inside it. That is good. Two methods can both have a variable called total without clashing. Pass data in through parameters and out through return values. Do not try to reach into another method's variables.

What makes a good method

  • It does one thing, and its name says what.
  • It fits on one screen.
  • It has few parameters. More than four usually means you need a class.
  • It avoids printing and calculating in the same place. Calculation methods that return values are easy to test. Printing methods are not.

Common mistakes

  • Forgetting to return a value on some path. The compiler reports "not all code paths return a value".
  • Ignoring the result. Calling CalculateTotal(3, 10m); as a statement computes and discards the answer.
  • Passing arguments in the wrong order. Two ints in a row are easy to swap. Named arguments protect you.
  • Methods that do too much. If you need "and" to describe it, split it.

Try it yourself

  1. Write IsPrime(int n) that returns true for prime numbers. Use it to print all primes below 50.
  2. Write Average(List<int> numbers) that returns a double and returns 0 for an empty list.
  3. Write Capitalise(string text) that makes the first letter uppercase and the rest lowercase.
  4. Take any earlier program of yours and move its calculation into a method.
csharp
decimal total = CalculateTotal(3, 49.99m);
Console.WriteLine($"Total with tax: {total:N2}");

PrintGreeting("Ayesha");
PrintGreeting("Bilal", excited: true);

Console.WriteLine(IsEven(10));
Console.WriteLine(IsEven(7));

var (min, max) = FindRange(new[] { 4, 9, 2, 7 });
Console.WriteLine($"Min {min}, max {max}");

Console.WriteLine(Factorial(5));

// Methods in top-level programs go below the statements
static decimal CalculateTotal(int quantity, decimal unitPrice, decimal taxRate = 0.17m)
{
    decimal subtotal = quantity * unitPrice;
    return subtotal + subtotal * taxRate;
}

static void PrintGreeting(string name, bool excited = false)
{
    string ending = excited ? "!" : ".";
    Console.WriteLine($"Hello, {name}{ending}");
}

static bool IsEven(int number) => number % 2 == 0;

static (int Min, int Max) FindRange(int[] numbers)
{
    int min = numbers[0];
    int max = numbers[0];
    foreach (int n in numbers)
    {
        if (n < min) min = n;
        if (n > max) max = n;
    }
    return (min, max);
}

static long Factorial(int n)
{
    if (n <= 1) return 1;
    return n * Factorial(n - 1);
}

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account