Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 182 ยท Methods

Methods

Learn how to write and call C# methods - declaration syntax, parameters and arguments, return values, void, overloading, method signatures, naming rules, static vs instance methods and XML docs.

A method is a named block of code that you can run whenever you need it. Instead of copying the same ten lines in five places, you give them a name, such as CalculateTax or PrintReceipt, and call that name. Methods are the basic unit of reuse in C#: every program you have written so far has used them (Console.WriteLine is a method), and every class you will write is mostly made of them.

Good methods do one job, have a name that says which job, and hide the details from the caller. In this lesson you will learn the full syntax of a method, how arguments reach parameters, how values come back, how several methods can share one name (overloading), the difference between static and instance methods, and how to document a method so editors show help for it.

Declaring and calling a method

A method declaration has a return type, a name, a parameter list in parentheses and a body in braces:

TEXT
returnType MethodName(parameterType parameterName, ...)
{
    // statements
    return value;    // if returnType is not void
}

You call a method by writing its name followed by arguments in parentheses. The values you pass in the call are arguments; the variables that receive them inside the method are parameters. People mix the two words up constantly, and nobody minds, but the distinction is useful: parameters are declared once, arguments are supplied on every call.

C# Your first methods

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

A method that returns nothing uses the return type void. A method that returns a value must reach a return value; statement on every path that can finish normally; the compiler checks this for you.

Methods you write directly in a top-level-statements file are local functions (see Expression-Bodied Members and Local Functions). Methods in a real program usually live inside a class. The examples later in this lesson show both, and Program Structure explains how the two fit together.

Return values and early returns

return ends the method immediately and hands a value back to the caller. A method may have many return statements. Early returns (also called guard clauses) handle special cases first and keep the main logic flat instead of nested in else branches:

C# Early returns

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The sentinel -1 in FirstEven works, but it is a trap: the caller must remember that -1 means "not found". Better designs are int? (see Nullable Value Types), the TryXxx pattern from Parameters, or an exception when "not found" really is an error.

If a path can fall off the end of a non-void method, the compiler refuses:

C# A path without a return (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The error is error CS0161: 'Sign(int)': not all code paths return a value. Add a final return "zero"; and it compiles.

Parameters and what a call really does

Think of each argument being copied into its parameter. For an int, double or bool the copy is the value itself, so changing the parameter inside the method never changes the caller's variable. For a reference type (a class, an array, a List<T>), what is copied is the reference: both names point to the same object, so changes to the object's contents are visible to the caller, but re-pointing the parameter to a new object is not.

C# Copies and references

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

If you want a method to change the caller's variable itself, C# has the keywords ref, out and in; they are the topic of Parameters: ref, out, in and params. For now, the rule of thumb is: prefer to return a new value instead of modifying arguments. Methods that take inputs and return an output, touching nothing else, are easy to test and reason about.

Validating arguments

A public method can't trust its callers. Check arguments at the top and fail loudly with the standard exceptions (ArgumentNullException, ArgumentOutOfRangeException, ArgumentException). .NET has throw-helpers that make this one line:

C# Guarding arguments

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Overloading and method signatures

The signature of a method is its name plus the types and kinds of its parameters (ref, out, in count; parameter names and the return type do not). Two methods in the same scope may share a name as long as their signatures differ. This is overloading, and it is how Console.WriteLine accepts a string, an int, a bool and a dozen other types.

When you call an overloaded method the compiler picks the best match at compile time: an exact type match wins over one that needs a conversion, and a more specific conversion wins over a less specific one.

C# Overload resolution

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Overloading works on methods that are members of a type. Local functions (the style used in the first examples of this lesson) cannot be overloaded: two local functions with the same name in one scope give error CS0128. That is why this example uses static class declarations placed after the statements.

Notice that Area(3) calls the one-parameter version, which calls the two-parameter version. Letting the simple overloads delegate to one "real" implementation keeps behavior consistent.

Overloads cannot differ only by return type, because the compiler can't tell which one you meant from the call alone:

C# Same signature (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The compiler reports error CS0111: Type 'Converter' already defines a member called 'Parse' with the same parameter types. Give the methods different names (ParseInt, ParseDouble).

Overloading is for the same operation on different inputs. If the methods do different things (Load(string path) reads a file but Load(string name) reads a database row), the types alone can't express it. Use distinct names. A few well-named methods beat many clever overloads, and Optional and Named Arguments shows an alternative to piles of overloads.

static and instance methods

A static method belongs to the type itself: you call it as TypeName.Method(), with no object. An instance method works on one particular object and can read that object's fields; you call it on a variable: account.Deposit(10). A static method has no this, so it can only use its parameters and other static members.

C# Static and instance methods

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Choose static when a method needs no object state: pure calculations, factory helpers, utility functions. Choose instance when the method reads or changes the object. Static classes are covered in Static Members and Static Classes, and objects in Classes and Objects.

Naming and design habits

  • Methods are verbs in PascalCase: CalculateTotal, SendEmail, IsValid. Methods that return bool read well as questions (IsEmpty, HasItems, CanRetry). Async methods end in Async.
  • One job per method. If you need "and" to describe it, split it. A useful test: can you name it without using and?
  • Keep the parameter list short. Past three or four parameters, group related values into a record or a small class.
  • Avoid surprises. A method named GetTotal should not change anything. Methods that change state should be named for the change (AddItem, Clear).
  • Return, don't print. Add(2, 3) should return 5; the caller decides whether to print it. Only methods whose job is output (PrintReceipt) should write to the console.
  • Keep them short. A method that fits on one screen is easier to read, test and reuse.

Documenting methods with XML comments

A comment made of three slashes (///) directly above a method is an XML documentation comment. Editors read it to show tooltips and parameter help when someone calls your method, so it is worth writing for any public member. The most useful tags are <summary>, <param name="...">, <returns>, and <exception cref="...">. (The tags are covered in Comments and XML Documentation.)

C# A documented method

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Hover over Percentage.Of in an IDE such as Visual Studio, Rider or VS Code and the summary, parameter notes and exception list appear as a tooltip. Our browser editor doesn't show tooltips, but the comment compiles and runs normally.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the difference between a parameter and an argument?

    Parameters are the variables in the method declaration. Arguments are the actual values supplied when the method is called.
  2. 2. Which of these is part of a method's signature?

    A signature is the name plus the parameter types (and ref/out/in kinds). Return type and parameter names do not count, which is why overloads can't differ only by return type.
  3. 3. After void Change(int x) { x = 5; } is called as Change(n); with int n = 1;, what is n?

    int is a value type, so the method receives a copy. The caller's variable is untouched.
  4. 4. When must a method be static?

    Static or instance is a design choice. A static method belongs to the type and can only use its parameters and other static members.
  5. 5. Which call picks the Show(double) overload when the available overloads are Show(int), Show(double) and Show(object)?

    A float has no exact overload but widens implicitly to double, which beats boxing to object. An int matches Show(int) and a char widens to int. A string only fits object.

Summary

  • A method has a return type, a name, parameters and a body; call it with arguments. void means it returns nothing.
  • Arguments are copied into parameters. Value types are copied entirely; for reference types the reference is copied, so the object is shared.
  • Use early returns for special cases and make every path of a non-void method return (error CS0161 otherwise).
  • Overloading lets one name serve several signatures (name + parameter types). The return type is not part of the signature.
  • static methods belong to the type; instance methods work on an object and can use this.
  • Name methods as PascalCase verbs, keep them short and focused, validate public arguments and return values instead of printing them.
  • /// XML comments feed editor tooltips and generated documentation.

Next: Parameters: ref, out, in and params