Turn repeated work into methods; learn parameters, return values, default values, overloading and recursion.
What is a method?
A method is a piece of code that has a name and runs when it is called. If you do the same calculation in three places in the program, write it once as a method and call it from three places. It gives you both brevity and fewer mistakes: if a fix is needed, you make it in one place.
static void Greet()
{
Console.WriteLine("Hello!");
}
Greet();
Greet();
void says that the method does not return a value. In a program written with top-level statements, you can define methods anywhere in the file and call them.
Parameters and return values
You can pass data to a method in parentheses and get a result back with return. Let's turn Ohm's law into a method:
static double OhmCurrent(double voltage, double resistance)
{
return voltage / resistance;
}
double current = OhmCurrent(12, 470);
Console.WriteLine($"Current: {current:F4} A");
Current: 0.0255 A
A method signature consists of these parts: the return type (double), the name (OhmCurrent), and the parameters (double voltage, double resistance). Starting method names with a capital letter is a C# convention.
Connecting methods together
static double OhmCurrent(double v, double r) => v / r;
static double Power(double v, double i) => v * i;
double v = 12, r = 470;
double i = OhmCurrent(v, r);
Console.WriteLine($"Power: {Power(v, i):F3} W");
Power: 0.306 W
You can write single-expression methods in short form with => (expression-bodied). Power P = V × I = 12 × 0.02553 ≈ 0.306 W.
Default and named parameters
static double Efficiency(double output, double input, int digits = 1)
{
return Math.Round(output / input * 100, digits);
}
Console.WriteLine(Efficiency(4.5, 5)); // 90
Console.WriteLine(Efficiency(4.567, 5, digits: 2)); // 91.34
A parameter with a default value can be left out in the call. A named argument (digits: 2) shows clearly which value belongs to what and prevents mixing up the order.
Overloading
Several methods with the same name can live together if their parameter lists are different. (Local methods defined inside top-level code cannot be overloaded; that is why we put the methods inside a class. You will see classes in detail in the next lesson.)
Console.WriteLine(Geometry.Area(2).ToString("F2")); // circle: 12.57
Console.WriteLine(Geometry.Area(3, 4)); // rectangle: 12
static class Geometry
{
public static double Area(double radius) => Math.PI * radius * radius;
public static double Area(double width, double height) => width * height;
}
out and multiple return values
A method returns a single value; if you need more than one value, you use an out parameter or a tuple. The tuple is more readable:
static (double Min, double Max) MinMax(double[] data)
{
double min = data[0], max = data[0];
foreach (double d in data)
{
if (d < min) min = d;
if (d > max) max = d;
}
return (min, max);
}
var result = MinMax(new double[] { 3.3, 2.9, 3.6, 3.1 });
Console.WriteLine($"Lowest: {result.Min}, highest: {result.Max}");
Lowest: 2.9, highest: 3.6
Recursion
A method can call itself. It must have a stopping condition. The classic example is the factorial: 5! = 5 × 4 × 3 × 2 × 1.
static long Factorial(int n)
{
if (n <= 1) return 1; // stopping condition
return n * Factorial(n - 1); // call itself with a smaller number
}
Console.WriteLine(Factorial(5));
120
Warning: If you forget the stopping condition, the method calls itself forever and the program crashes with a "StackOverflow". Instead of very deep recursion, use a loop when possible.
A good method: A method should do a single job, and its name should describe that job. Instead of "CalculateAndPrintAndSave", write three separate methods. This makes testing and changing easier.
Try it yourself
Write the methods SeriesResistance(double r1, double r2) and ParallelResistance(double r1, double r2). Then, in your top-level code, take two resistance values from the user and print both results. Bonus: write an overloaded version that takes a double[].
// Mini quiz
Click an option; you will see right away, with the reason, whether it is correct or not.
Mark it when you finish: your progress is saved and you earn +20 XP.
Tip: ← → keys let you move between lessons.