BeginnerLesson 5 of 16
Methods – C#
Reusable building blocks of code with parameters and return values.
A method has a return type, a name and parameters. With top-level statements you define them as local functions; with => you write short methods as an expression. Parameters may have default values and can be addressed by name.
Console.WriteLine(Begruesse("Ada"));
Console.WriteLine(Begruesse("Linus", gruss: "Hi"));
static string Begruesse(string name, string gruss = "Hello") => $"{gruss}, {name}!";You return multiple values as a tuple, params collects any number of arguments, and lambda expressions are small anonymous methods:
var (min, max) = MinMax(new[] { 4, 9, 2 });
Console.WriteLine($"{min} {max}"); // 2 9
Console.WriteLine(Summe(1, 2, 3, 4)); // 10
Func<int, int> quadrat = x => x * x;
Console.WriteLine(quadrat(7)); // 49
static (int Min, int Max) MinMax(int[] werte) => (werte.Min(), werte.Max());
static int Summe(params int[] zahlen) => zahlen.Sum();With out you return additional values through parameters (this is how TryParse works); with ref you pass a variable by reference instead of as a copy.
static bool TeileDurch(int a, int b, out int ergebnis)
{
ergebnis = 0;
if (b == 0) return false;
ergebnis = a / b;
return true;
}
if (TeileDurch(10, 2, out int q)) Console.WriteLine(q); // 5TipLocal functions may appear after the statements in which you call them. Custom types (
class, record, enum), however, must come after all top-level statements.