Methods
A method in a class
A method is a named block with parameters and, usually, a return value. In a class it is a member, and the modifier decides how it is called: static means it belongs to the type and is called as Program.Area(2), while a method without it belongs to an instance and needs an object.
class Program
{
static void Main()
{
Console.WriteLine(Add(2, 3));
Console.WriteLine(Add(2.5, 3.5));
Console.WriteLine(Describe());
Console.WriteLine(Describe("Ada"));
Console.WriteLine(Area(2));
}
static int Add(int a, int b) => a + b;
static double Add(double a, double b) => a + b;
static string Describe() => "nobody";
static string Describe(string name) => $"name: {name}";
static double Area(double radius) => Math.PI * radius * radius;
}
dotnet run
5
6
nobody
name: Ada
12.566370614359172
Two pairs of the methods share a name and differ in their parameters: that is an overload. The compiler picks the one whose parameter types fit the arguments, and Add(2, 3) goes to the int version while Add(2.5, 3.5) goes to the double one. Overloads must differ in their parameters; a different return type alone is not enough.
Overloading
The rules of overload resolution are worth knowing because a surprising call is a common bug:
- An exact match wins over a conversion: Add(1, 2) takes the int overload even when a long one exists.
- A conversion that loses information — double to int — is not applied implicitly, so Add(2.5, 3) is ambiguous rather than silently truncated.
- Overloads may differ in the number of parameters, their types, or both; optional parameters (the lesson after the next) take part too.
A method that only computes a value and reads no field is static, and a static method may be called without an object. A method that reads or writes the state of an object is an instance method, and the part on classes shows the call through an object.
Why local functions cannot be overloaded
A top-level program may declare functions too, and they are local functions of the generated Main. A local namespace has no overloads: two functions with the same name are one name declared twice, and the compiler says so.
Console.WriteLine(Add(2, 3));
Console.WriteLine(Add(2.5, 3.5));
static int Add(int a, int b) => a + b;
static double Add(double a, double b) => a + b;
dotnet build
Program.cs(2,23): error CS1503: Argument 1: cannot convert from 'double' to 'int'
Program.cs(2,28): error CS1503: Argument 2: cannot convert from 'double' to 'int'
Program.cs(6,15): error CS0128: A local variable or function named 'Add' is already defined in this scope
Program.cs(6,15): warning CS8321: The local function 'Add' is declared but never used
Build FAILED.
The second Add is not a second overload but a redeclaration, so the first one stays the only candidate and the double call cannot convert. The fix is a class with two methods, as in the first program, or two different names. The warning CS8321 follows the error: the compiler sees a function nothing calls.
Guard clauses
A method with several conditions reads best with early returns: each guard handles one case and leaves the main path at the end.
Console.WriteLine(Classify(0));
Console.WriteLine(Classify(5));
Console.WriteLine(Classify(-2));
Console.WriteLine(Repeat("ha", 3));
static string Classify(int n)
{
if (n == 0)
{
return "zero";
}
if (n < 0)
{
return "negative";
}
return "positive";
}
static string Repeat(string text, int times)
{
var result = new System.Text.StringBuilder();
for (int i = 0; i < times; i++)
{
result.Append(text);
}
return result.ToString();
}
dotnet run
zero
positive
negative
hahaha
Every path of Classify ends in a return, which is what the compiler checks: a method that returns a value and has a path with no return is CS0161: not all code paths return a value. A guard that throws instead of returning is ArgumentNullException.ThrowIfNull(name) at the top of a method, which the part on exceptions reads.
Exercises
- Add a Add(long, long) overload to the first program and call Add(1, 2). Which overload runs, and how do you know?
- Call Add(2.5, 3) against the two overloads. Read the error about the ambiguity.
- Give Classify a path with no return and read CS0161.
- Rewrite Repeat with string.Concat(Enumerable.Repeat(text, times)) and compare the two.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Which method does the compiler call for Add(1, 2) when Add(int, int) and Add(long, long) both exist?
Answer
Add(int, int), because it is an exact match
An exact match is preferred to a conversion, so the int overload wins without a widening.
-
What is an overload?
Answer
A method with the same name and different parameters
The name is shared and the parameter list differs, which is what lets the compiler choose by the arguments.
-
What does this program print?
Console.WriteLine(Add(2, 3)); Console.WriteLine(Add(2.5, 3.5)); static int Add(int a, int b) => a + b; static double Add(double a, double b) => a + b;Answer
error CS1503: Argument 1: cannot convert from 'double' to 'int'
Two local functions of one name are one name declared twice, so the first stays the only candidate and the double call cannot convert.
-
What does a static method need to be called?
Answer
The type name and the arguments
A static method belongs to the type, so Program.Area(2) is enough; an instance method needs an object.
-
What does this program print?
Console.WriteLine(Describe()); Console.WriteLine(Describe("Ada")); static string Describe() => "nobody"; static string Describe(string name) => $"name: {name}";Answer
error CS1501: No overload for method 'Describe' takes 1 arguments
The two local functions share a name, so the second declaration is CS0128 and the call with one argument finds no overload.
-
What does CS0161 report?
Answer
A method that returns a value has a path with no return
The compiler checks every path of a method that must return a value, and one missing return stops the build.
-
What does this program print?
Console.WriteLine(Classify(-2)); static string Classify(int n) { if (n == 0) return "zero"; if (n < 0) return "negative"; return "positive"; }Answer
negative
The second guard catches the negative value and returns before the last line is reached.
-
Can two methods differ only in their return type?
Answer
No: the parameter list must differ
Overload resolution looks at the name and the arguments, so the return type alone cannot tell two methods apart.
-
What does this program print?
Console.WriteLine(Repeat("ab", 2)); static string Repeat(string text, int times) { var result = new System.Text.StringBuilder(); for (int i = 0; i < times; i++) { result.Append(text); } return result.ToString(); }Answer
abab
The loop appends the text twice, and the fully qualified name needs no using.
-
Why is
Add(2.5, 3)against Add(int, int) and Add(double, double) a problem?Answer
The first argument fits only double and the second fits both, so the call is ambiguous
The compiler prefers an exact match per argument, and neither overload is exact for both, so no single best one exists.
The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev