Defining and calling a method
A method is a named block of code that takes some inputs (parameters), does one job and optionally hands back a result (its return value). The first line of a method, its signature, says all of that: static int Square(int n) reads "a method called Square that takes an int called n and returns an int". A method that returns nothing is declared void.
In a file-based C# program you can write a method in two places. Among the top-level statements, it is a local function: it belongs to the hidden Main and can be called from anywhere in the top-level code, even above where it is written. Inside a class, it is a normal method; mark it static when it does not need an object, and call it as ClassName.Method(). Real projects put almost every method on a type; small scripts and this handbook use both.
Greet("Ana");
Console.WriteLine(Square(7));
Console.WriteLine(MathUtil.Cube(3));
Console.WriteLine(MathUtil.IsEven(10));
// local functions: callable anywhere in the top-level code
static void Greet(string name)
{
Console.WriteLine($"Hello, {name}!");
}
static int Square(int n)
{
return n * n;
}
// a static method on a class: called as MathUtil.Cube(...)
static class MathUtil
{
public static int Cube(int n) => n * n * n;
public static bool IsEven(int n) => n % 2 == 0;
}Hello, Ana!
49
27
TrueAdd a method static double Average(int a, int b) to MathUtil and print MathUtil.Average(3, 4). Why does (a + b) / 2 print 3 instead of 3.5?
The return statement ends the method immediately and hands the value back. A method declared to return int must return an int on every path through it; the compiler checks this, and a missing return after an if is one of the first errors every beginner meets.
CS0161: not all code paths return a value
Console.WriteLine(Sign(-4));
static string Sign(int n)
{
if (n > 0) return "positive";
if (n < 0) return "negative";
}Program.cs(3,15): error CS0161: 'Sign(int)': not all code paths return a valueWhen n is 0, neither if matches and execution falls off the end of the method with no string to hand back. C# does not invent a default value, so it refuses to compile. The compiler does not try to prove that one of your conditions is always true; it only follows the paths.
Make the last path return something (or throw). A final return with no condition, or a switch expression with a _ arm, covers every case.
Console.WriteLine(Sign(-4));
static string Sign(int n)
{
if (n > 0) return "positive";
if (n < 0) return "negative";
return "zero";
}CalculateTotal, IsValid, TryParse. Parameters and locals are camelCase. A method whose name starts with Is, Has or Can should return bool.