Functions in C#: Methods, Parameters, ref/out and Local Functions (.NET 10)

To write functions in C#, you declare a method: a return type, a name, parameters in parentheses and a body. C# calls every function a method, and in a .NET 10 file-based app you can write one right next to your top-level code:

decimal Total(decimal price, int cups) => price * cups;

Console.WriteLine(Total(4.75m, 3));   // 14.25

Quick answer: use a static method when it only needs its parameters, an instance method when it works on an object’s data, and out or a tuple to send back two values. Every example below ran on .NET 10.

What Is a Function (Method) in C#?

A method is a named block of code you call to do one job. You give it inputs (parameters), and it can hand back a result (the return value). If it returns nothing, its return type is void.

The pieces of a declaration, left to right:

PartExampleNotes
Access modifierpublicOptional; a class member defaults to private
Modifiersstatic, async, virtualOptional
Return typedecimal or voidMust match what return sends back
NameAddSalesTaxPascalCase verb
Parameters(decimal amount)Empty () when there are none

Names follow the PascalCase verb style from the C# method naming conventions. My running sample is a coffee order in Austin, Texas: three lattes at $4.75 for Jenna Morales, plus the city’s 8.25% sales tax.

using System.Globalization;
CultureInfo.CurrentCulture = new CultureInfo("en-US");

// One order at an Austin coffee shop
decimal subtotal = Subtotal(4.75m, 3);
decimal total = AddSalesTax(subtotal);
PrintReceipt("Jenna Morales", total);

static decimal Subtotal(decimal price, int cups)
{
    return price * cups;
}

static decimal AddSalesTax(decimal amount) =>
    Math.Round(amount * 1.0825m, 2);   // Austin, TX: 8.25%

static void PrintReceipt(string customer, decimal total) =>
    Console.WriteLine($"{customer} pays {total:C}");

Output:

Jenna Morales pays $15.43
Functions in C#: Subtotal, AddSalesTax and PrintReceipt methods for a coffee order, with the receipt output in the VS Code terminal
Three small methods: one multiplies, one adds tax, one prints. Output: Jenna Morales pays $15.43

Each call’s return value feeds the next one: Subtotal returns 14.25, AddSalesTax turns that into 15.43, and PrintReceipt is void because it only writes to the console.

Note: in a file with top-level statements, these are local functions of the generated Main. That’s why they need no class. Inside a class, the same code is an ordinary method.

Built-in methods work the same way. Math.Round and Console.WriteLine are just methods someone at Microsoft wrote, and the values you pass them are regular variables or literals.

Static vs Instance Methods in C#

An instance method belongs to one object and can read that object’s fields. A static method belongs to the type itself, so you call it on the class name and it can’t see any one object’s data.

Same order, now inside an Order class for Tyler Brooks, who adds a $3.50 muffin:

using System.Globalization;
CultureInfo.CurrentCulture = new CultureInfo("en-US");

var order = new Order("Tyler Brooks", 14.25m);
order.AddItem(3.50m);                   // instance method
Console.WriteLine(order.Describe());
decimal taxed = Order.WithTax(17.75m);  // static method
Console.WriteLine($"With tax: {taxed:C}");

class Order(string customer, decimal subtotal)
{
    decimal _subtotal = subtotal;
    public void AddItem(decimal price) => _subtotal += price;
    public string Describe() => $"{customer}: {_subtotal:C}";
    public static decimal WithTax(decimal amount) =>
        Math.Round(amount * 1.0825m, 2);
}

Output:

Tyler Brooks: $17.75
With tax: $19.21
C# static vs instance method: order.AddItem and order.Describe called on an object, Order.WithTax called on the class, VS Code output
AddItem and Describe need the order object; WithTax is called on the Order type

AddItem changed this order’s subtotal from $14.25 to $17.75, and Describe read it back. Order.WithTax didn’t need an order at all and returned $19.21.

The Order(string customer, decimal subtotal) header is a primary constructor; constructors in C# covers the other forms. For how methods fit into classes, inheritance and polymorphism, see OOP concepts in C#.

Pro Tip: make a helper static whenever it doesn’t touch instance data. The compiler then stops you from using fields by accident, and callers don’t have to create an object first.

Parameters and Return Values

Parameters are the variables in the declaration; arguments are the values you pass when you call it. By default every argument is passed by value, so the method gets a copy.

A method returns one value with return, and that statement also ends the method. When you need several values, return a tuple or use out parameters, both shown a few sections down.

For work that waits on a file, database or web call, the return type becomes Task or Task<T> and you mark the method async. Those methods can’t take ref, out or in parameters.

Optional and Named Parameters

Give a parameter a default value and callers can skip it. Optional parameters must come after all required ones. Named arguments let a caller skip to the one it cares about, in any order.

Same coffee shop, now working out the tip on a $40 bill:

using System.Globalization;
CultureInfo.CurrentCulture = new CultureInfo("en-US");

Console.WriteLine(Tip(40.00m));                 // default 18%
Console.WriteLine(Tip(40.00m, 0.20m));          // positional
Console.WriteLine(Tip(40.00m, roundUp: true));  // named
var last = Tip(roundUp: true, bill: 37.60m, percent: 0.15m);
Console.WriteLine(last);

static string Tip(decimal bill, decimal percent = 0.18m,
                  bool roundUp = false)
{
    decimal tip = bill * percent;
    if (roundUp) tip = Math.Ceiling(tip);
    return $"{bill:C} bill, {percent:P0} tip = {tip:C}";
}

Output:

$40.00 bill, 18% tip = $7.20
$40.00 bill, 20% tip = $8.00
$40.00 bill, 18% tip = $8.00
$37.60 bill, 15% tip = $6.00
C# optional and named parameters: Tip method with default 18 percent and roundUp, called four ways, VS Code output
Defaults fill in what the caller leaves out; named arguments skip straight to roundUp

The default call used 18% ($7.20), and roundUp: true skipped percent without passing 0.18 again. The last call names all three arguments in a different order and still returns $6.00.

Important: default values must be compile-time constants. If you need several shapes of the same call with different types, method overloading in C# is usually cleaner than a long optional list.

ref, out and in Parameters: What’s the Difference?

These modifiers pass the variable itself (by reference) instead of a copy. They exist for three different jobs:

ModifierCaller must initialize?Method can change it?Use it for
refYesYesUpdating the caller’s variable
outNoMust assign before returningA second result, like TryParse
inYesNo (read-only)Large structs you don’t want copied
ref readonlyYesNoLike in, but the argument must be a variable (C# 12)

Here’s a reward-points balance of 120, a cup count parsed from text, and a tuple with the order’s stats:

int points = 120;
AddBonusCopy(points);
Console.WriteLine($"by value: {points}");
AddBonus(ref points);
Console.WriteLine($"ref:      {points}");

if (TryParseCups("3 cups", out int cups))
    Console.WriteLine($"out:      {cups} cups");

var (count, avg) = Stats([4.75m, 5.25m, 3.50m]);
Console.WriteLine($"tuple:    {count} items, avg {avg:F2}");

static void AddBonusCopy(int p) => p += 50;
static void AddBonus(ref int p) => p += 50;
static bool TryParseCups(string text, out int cups) =>
    int.TryParse(text.Split(' ')[0], out cups);
static (int Count, decimal Avg) Stats(decimal[] prices) =>
    (prices.Length, prices.Average());

Output:

by value: 120
ref:      170
out:      3 cups
tuple:    3 items, avg 4.50
C# ref, out and tuple return: by-value call leaves 120, ref adds 50 to make 170, out parses 3 cups, tuple returns 3 items avg 4.50, VS Code output
Only the ref call changed points; the copy passed by value was thrown away

AddBonusCopy added 50 to its own copy, so points stayed 120. AddBonus(ref points) changed the real variable to 170. Both the definition and the call must say ref.

TryParseCups follows the int.TryParse pattern: a bool for success and the number through out. For two results that always come together, I prefer the tuple: Stats returned 3 items and an average of 4.50 with no out at all.

params Parameters: Pass Any Number of Arguments

A params parameter collects a comma-separated list into one collection. It must be the last parameter, and a method can have only one. Since C# 13 it can be a ReadOnlySpan<T> or a List<T>, not only an array.

using System.Globalization;
CultureInfo.CurrentCulture = new CultureInfo("en-US");

Console.WriteLine(OrderTotal("Jenna Morales", 4.75m, 5.25m, 3.50m));
Console.WriteLine(OrderTotal("Tyler Brooks"));     // zero items is fine
decimal[] saved = [6.25m, 2.00m];
Console.WriteLine(OrderTotal("Carmen Diaz", saved));

static string OrderTotal(string customer, params ReadOnlySpan<decimal> prices)
{
    decimal sum = 0;
    foreach (decimal p in prices) sum += p;
    return $"{customer}: {prices.Length} items, {sum:C}";
}

Output:

Jenna Morales: 3 items, $13.50
Tyler Brooks: 0 items, $0.00
Carmen Diaz: 2 items, $8.25

Jenna’s three items add up to $13.50, Tyler’s empty call returned 0 items and $0.00 instead of throwing, and Carmen’s saved array of two prices passed straight through as $8.25. A span version avoids allocating an array for the comma-list call.

Local Functions and Expression-Bodied Methods

A local function is a method declared inside another method. Only that method can call it, which keeps a one-off helper next to the only code that uses it.

This one serves the morning line and calls itself until the queue runs out:

string[] queue = ["Jenna Morales", "Tyler Brooks", "Carmen Diaz"];
int served = 0;

ServeNext(0);
Console.WriteLine($"Served {served} of {queue.Length}");
Console.WriteLine($"Ways to line them up: {Factorial(queue.Length)}");

void ServeNext(int i)                 // captures queue and served
{
    if (i == queue.Length) return;    // stop condition
    Console.WriteLine($"Now serving {queue[i]}");
    served++;
    ServeNext(i + 1);                 // recursion
}

static int Factorial(int n) => n <= 1 ? 1 : n * Factorial(n - 1);

Output:

Now serving Jenna Morales
Now serving Tyler Brooks
Now serving Carmen Diaz
Served 3 of 3
Ways to line them up: 6

ServeNext captures queue and served from the surrounding code, so it needs no extra parameters. Factorial is marked static, which forbids capturing and keeps it honest. It returned 6 ways to line up three customers.

The => form you’ve seen throughout is an expression-bodied method: one expression, no braces, no return. I use it for one-liners and switch to braces once there’s an if or a loop. The recursion idea is the same one in the C# factorial program.

When the behavior is short and you’re passing it to another method, a lambda fits better; anonymous methods in C# and delegates in C# explain how a method becomes a value you can pass around.

Common Errors with C# Methods and How to Fix Them

I broke the coffee-shop code on purpose to show the two errors I see most often in code reviews:

var order = new Order();
Console.WriteLine(Order.Describe());   // called on the type
TryGetCups(out _);

static bool TryGetCups(out int cups)
{
    return false;                      // cups never assigned
}

class Order
{
    public string Describe() => "Order for Carmen Diaz";
}

Build output:

C:\DotNetDemo\Funcs\Errors.cs(2,19): error CS0120: An object reference is required for the non-static field, method, or property 'Order.Describe()'
C:\DotNetDemo\Funcs\Errors.cs(7,5): error CS0177: The out parameter 'cups' must be assigned to before control leaves the current method

The build failed. Fix the build errors and run again.
C# method compiler errors CS0120 object reference is required for the non-static method and CS0177 out parameter must be assigned, VS Code terminal
Calling an instance method on the class gives CS0120; returning without assigning an out parameter gives CS0177
ErrorCauseFix
CS0120Instance method called on the class nameCreate an object first, or make the method static
CS0177An out parameter isn’t assigned on every pathAssign it before each return
CS0161Not all code paths return a valueAdd a return (or throw) at the end
CS1737Optional parameter placed before a required oneMove optional parameters to the end
CS1620Argument for a ref parameter passed without refWrite ref at the call site too

Runtime failures are a different story: wrap the risky call, not the whole method, as shown in try catch in C#.

Which Kind of Method Should You Use?

  • A static method for calculations that only need their parameters (WithTax).
  • An instance method when the work reads or changes one object’s state (AddItem).
  • Optional parameters for sensible defaults; overloads when the parameter types differ.
  • A tuple for two or three related results; out for the Try pattern.
  • A local function for a helper only one method needs.

Keep each method to one job and a verb name, and you’ll rarely need more than these five patterns. These go deeper on the pieces around methods:

Frequently Asked Questions

Is a function the same as a method in C#?

Yes. C# has no free-standing functions; every named function is a method declared in a class, struct or record. Top-level statements and local functions look like free functions, but the compiler places them inside a generated method.

How do you call a function in C#?

Write its name followed by parentheses with the arguments, like Subtotal(4.75m, 3). For an instance method, call it on an object (order.AddItem(3.50m)); for a static method, call it on the type (Order.WithTax(17.75m)).

How can a C# method return multiple values?

Return a tuple such as (int Count, decimal Avg), use out parameters, or return a small record or class. Tuples are the simplest for two or three related values.

What is the difference between ref and out in C#?

A ref argument must be initialized before the call and the method may change it. An out argument doesn’t need a value first, but the method must assign it before returning. Details are in Method parameters and modifiers on Microsoft Learn.

Can a C# method have default parameter values?

Yes. Write decimal percent = 0.18m in the declaration. Default values must be compile-time constants, and optional parameters must come after required ones.

When should a method be static in C#?

Make it static when it doesn’t use instance fields or properties. Static methods are called on the type name and can’t be called through an object.