C# · Basics

Methods

A method is a named block of code you can call again and again. Write the logic once, give it a good name, and your program reads like a list of clear instructions.

Beginner 6 min Lesson 7 of 26Examples target C# 13 on .NET 9 unless stated otherwise.
Before you start:Loops
0/26 in C#
On this page · 6 min · Beginner

In simple words#

A method is a recipe card with a name. You hand it ingredients (parameters), it follows the steps, and gives you back a dish (return value). Write it once, cook it many times.

Method
A named block of reusable code.
Parameter
An input the method needs.
Return value
The result the method gives back.

Learning objectives#

  • Declare methods with parameters and a return type
  • Use void for methods that return nothing
  • Use default, named and out parameters
  • Write short expression-bodied methods

Explanation#

A method has a return type, a name, parameters in brackets and a body: int Add(int a, int b) { return a + b; }.

void means the method does an action but returns no value, like printing a line.

Default parameters make arguments optional: string Greet(string name, string greeting = "Hello"). Named arguments (Area(width: 5, height: 2)) make calls self-explanatory.

For one-line methods use =>: int Add(int a, int b) => a + b;. This is called an expression-bodied method.

An out parameter lets a method return an extra value. The Try pattern (bool TryParse(string s, out int value)) uses it to report success without throwing an exception.

In a top-level program, methods go after your statements. In a class they go inside the class body.

Syntax#

C# Illustrative
returnType Name(type param1, type param2 = defaultValue)
{
    return value;
}


int Square(int n) => n * n;   // expression-bodied

Code example: Five kinds of method#

C#Program.cs Illustrative
Console.WriteLine(Add(3, 4));
Console.WriteLine(Greet("Asha"));
Console.WriteLine(Greet("Ravi", "Good morning"));
Console.WriteLine(Area(height: 2, width: 5));
PrintLine();


if (TryDivide(10, 3, out int answer))
    Console.WriteLine(
quot;10 / 3 =
{answer}");
if (!TryDivide(10, 0, out _)) Console.WriteLine("Cannot divide by zero"); static int Add(int a, int b) => a + b; static string Greet(string name, string greeting = "Hello") =>
quot;
{greeting}, {name}!";
static double Area(double width, double height) { return width * height; } static void PrintLine() { Console.WriteLine("----------"); } static bool TryDivide(int a, int b, out int result) { if (b == 0) { result = 0; return false; } result = a / b; return true; }
Expected output
7
Hello, Asha!
Good morning, Ravi!
10
----------
10 / 3 = 3
Cannot divide by zero

This example is illustrative. Copy or download it and run it in your own environment; the expected output is shown above.

Step-by-step explanation#

  1. Add takes two ints and returns their sum with the short => form.
  2. Greet has a default greeting, so it can be called with one argument or two.
  3. Area is called with named arguments in a different order — names make the order irrelevant.
  4. PrintLine is void: it does something but returns nothing.
  5. TryDivide returns true or false and hands back the result through out int answer. out _ discards a value you do not need.

Real-world use case#

An ASP.NET Core service has methods such as CalculateShipping(order), SendInvoiceEmail(customer) and TryApplyCoupon(code, out discount). Each does one job, so each can be tested on its own.

Common mistakes#

Not all code paths return a value

A method with a return type must return on every path. Add the missing return or throw.

Methods that do too much

A 200-line ProcessOrder is hard to test and reuse. Split it into ValidateOrder, ChargePayment and SendConfirmation.

Expecting parameters to change the caller’s variable

Ordinary parameters are copies. Changing a in Add does not change the caller’s variable. Return the new value instead.

Best practices#

  • Name methods with verbs in PascalCase (CalculateTotal)
  • Keep methods short and focused on one task
  • Use the Try pattern instead of exceptions for expected failures
  • Prefer returning a value over out parameters when there is only one result

Remember this#

Method = name + inputs (parameters) + output (return type).

void = does something, returns nothing.

TryXxx(..., out value) returns bool: “did it work?”.

Practice exercise#

Your task: Write a method IsEven(int n) that returns a bool, and a method Describe(int n) that returns "4 is even" or "7 is odd" using IsEven.

Need a hint?
IsEven is one line: n % 2 == 0. Describe can use the ternary operator.
Show solution
C# Illustrative
Console.WriteLine(Describe(4));   // 4 is even
Console.WriteLine(Describe(7));   // 7 is odd


static bool IsEven(int n) => n % 2 == 0;
static string Describe(int n) => 
quot;
{n} is {(IsEven(n) ? "even" : "odd")}";

Mini quiz#

Methods quizMultiple choice Question 1 of 3

What does void mean in front of a method name?

Score so far: 0/0

Want more? Practise all C# MCQs · C# interview questions

My notes#

Saved in this browser.

Progress is saved in this browser. Sign in to sync.