Beginner · Decisions, loops and methods · topic 8 of 43 · 30 min
Methods: write once, use many times
Explanation
Why methods?
You have already called methods that .NET gives you: Console.WriteLine, int.Parse and Math.Round. A method is a named block of code that does one job. When you write your own, you can reuse the steps by calling the name. If the GST rate changes, you fix one method instead of twenty copies.
The parts of a method
static decimal AddGst(decimal price, decimal rate)
{
decimal gst = price * rate;
return price + gst;
}| Part | Meaning |
|---|---|
| Return type | The type of value the method gives back; void if it gives back nothing |
| Name | PascalCase, usually a verb: CalculateTotal, PrintReceipt, IsValidPin |
| Parameters | Inputs, each with a type and a name, separated by commas |
| Body | The statements in { } |
| return | Ends the method and hands the value back to the caller |
Calling a method
decimal total = AddGst(1000m, 0.18m);
Console.WriteLine(total); // 1180.00
Console.WriteLine(AddGst(500m, 0.05m)); // 525.00
static decimal AddGst(decimal price, decimal rate)
{
return price + price * rate;
}Values you pass when calling (1000m, 0.18m) are called arguments. They are copied into the parameters (price, rate) in the same order.
void methods
PrintLine('=', 20);
Console.WriteLine(" BILL");
PrintLine('=', 20);
static void PrintLine(char symbol, int length)
{
Console.WriteLine(new string(symbol, length));
}Expression-bodied methods
static int Square(int n) => n * n;
static bool IsAdult(int age) => age >= 18;
static void Greet(string name) => Console.WriteLine($"Hi {name}");Every path must return
static string Result(int marks)
{
if (marks >= 40)
return "Pass";
// error CS0161: not all code paths return a value
}Local variables and scope
A variable declared inside a method is local: it exists only while the method runs and only inside its braces. Two methods can both have a variable named total without any clash. This is called scope: the region of code where a name can be used.
Returning more than one value with a tuple
var (each, left) = SplitBill(1000, 3);
Console.WriteLine($"Each pays {each}, {left} rupee left");
static (int Each, int Left) SplitBill(int total, int people)
=> (total / people, total % people);Recursion, briefly
static long Factorial(int n) => n <= 1 ? 1 : n * Factorial(n - 1);
Console.WriteLine(Factorial(5)); // 120Common mistakes and fixes
- Printing instead of returning: a method named CalculateTotal that only prints cannot be used in further sums. Return the value and let the caller print.
- Forgetting to use the return value: AddGst(price, rate); on its own line throws the answer away. Store it: price = AddGst(price, rate);
- Methods that do five jobs: split them. A good method fits on one screen and its name says exactly what it does.
- Wrong argument order: AddGst(0.18m, 1000m) compiles but gives the wrong answer. Named arguments (next topic) help.
Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
Methods: write once, use many times · 1/7
In this lesson you will write your own methods: named blocks of code that do one job.
Prefer a video by a teacher? Find free videos on “C# methods parameters return values static methods beginners” on YouTube ↗
In real life: A Zomato-style delivery charge
A food delivery app charges delivery by distance and waives it for big orders. Putting the rule in one method means the pricing team can change it in one place, and testers can check it with many values.
Console.WriteLine(DeliveryCharge(2.5, 150m)); // 25
Console.WriteLine(DeliveryCharge(7.0, 300m)); // 55.0
Console.WriteLine(DeliveryCharge(7.0, 600m)); // 0
static decimal DeliveryCharge(double km, decimal orderValue)
{
if (orderValue >= 499m) return 0m; // free delivery on big orders
if (km <= 3) return 25m;
return 25m + (decimal)Math.Ceiling(km - 3) * 7.5m;
}Practice (0/4 done)
static int Twice(int n) => n * 2; What does Console.WriteLine(Twice(4) + 1); print?
Which method header is correct for a method that returns nothing?
Why does this not compile? static bool IsEven(int n) { if (n % 2 == 0) return true; }
Write three methods for a school report: Total(int a, int b, int c) returns the total, Percentage(int total, int maxTotal) returns a double percentage, and Grade(double percent) returns "A" (90+), "B" (75+), "C" (40+) or "F" using a switch expression. Call them for marks 85, 92 and 78 out of 300.
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Parameters in depth: optional, named, ref, out, params, overloadingDecisions, loops and methods · same module
- FunctionsFrontend Web Development · JavaScript basics
- Methods: parameters, return values and overloadingJava Programming (Core to Spring Boot) · Control flow and methods
- FunctionsC Programming (from zero to systems) · Functions and arrays
- Functions: declare, define, call and returnC++ Programming (modern C++ and DSA) · Decisions, loops and functions
- Arrow functionsJavaScript Programming (language in depth) · Functions and closures
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
What is the difference between a parameter and an argument?
Answer: A parameter is the name in the method header; an argument is the value passed when calling
Parameters are the placeholders; arguments are the actual values.
What does return do?
Answer: Ends the method and gives a value back to the caller
return ends the method immediately and hands back the value.
Which is a good method name in C#?
Answer: CalculateTotal
C# methods use PascalCase and usually start with a verb.
A variable declared inside a method can be used...
Answer: Only inside that method (its scope)
Local variables exist only inside the method that declares them.
What is needed for a recursive method to stop?
Answer: A base (stopping) case that does not call itself
Without a base case, the calls never end and the stack overflows.
A variable is declared with const inside a function. Where can it be used?Related
Answer: Only inside that function
let and const are block-scoped: they live only inside their { }.
From Functions
What does void mean in a method declaration?Related
Answer: The method returns no value
void methods do not return a value.
A non-void function ends without return on one branch, and the caller uses the result. This is…Related
What does void as a return type mean?Related
Answer: The function returns nothing
void functions do their job without giving a value back.
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- 1 more topic in “Decisions, loops and methods” before its exam: Parameters in depth: optional, named, ref, out, params, overloading.
- Module 2 exam: Decisions, loops and methods · 13 questions · 20 min, without help. 4 topics of this module still to finish first.
- Then the next module, Arrays, strings and null. 43 topics left in the course before the final exam.