Methods: Reuse Your Code

Dot NET Programming 14 min min read Updated: Nov 16, 2026 Beginner
Methods: Reuse Your Code
Beginner Topic 6 of 9

What is a Method?

A method is a named block of code you can call many times. It keeps programs short and tidy: write once, use everywhere.

csharp void SayHello() { Console.WriteLine("Hello!"); } SayHello(); SayHello();

Parameters and Return Values

csharp int Add(int a, int b) { return a + b; } int total = Add(3, 4); // 7 Console.WriteLine(Add(10, 20)); // 30
PartMeaning
int (before the name)Return type. void means returns nothing.
AddMethod name, in PascalCase
(int a, int b)Parameters: the inputs
returnSends the result back and ends the method

Expression-Bodied Methods

csharp int Square(int x) => x * x; string Greet(string name) => $"Hello, {name}!";

Overloading: Same Name, Different Parameters

csharp double Area(double radius) => Math.PI * radius * radius; double Area(double width, double height) => width * height; Console.WriteLine(Area(2)); // circle Console.WriteLine(Area(2, 3)); // rectangle

Returning Several Values with a Tuple

csharp (int Min, int Max) FindRange(int[] numbers) { return (numbers.Min(), numbers.Max()); } var (low, high) = FindRange(new[] { 4, 9, 1 }); Console.WriteLine($"{low} - {high}"); // 1 - 9

Local Functions

csharp int SumOfSquares(int[] items) { int total = 0; foreach (var x in items) total += Square(x); return total; static int Square(int n) => n * n; // only visible inside SumOfSquares }

Recursion: A Method Calling Itself

csharp int Factorial(int n) { if (n <= 1) return 1; // stop condition return n * Factorial(n - 1); } Console.WriteLine(Factorial(5)); // 120
Always have a stop condition: A recursive method without one calls itself until the program crashes with a StackOverflowException.

Good Method Habits

  • One method, one job
  • Name it with a verb: CalculateTotal, SendEmail
  • Keep parameters few (three or fewer is a good goal)
  • Avoid very long methods. Split them.

Conclusion

Methods give names to pieces of logic. Use parameters for inputs, return values for results and keep each method small and focused.

Quick Summary: Return type, name, parameters, body. Overload with different parameters. Return tuples for several values.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators