Methods
9 min · C#
Package code under a name so you can reuse it (C# calls them methods).
Enemy 1 of 5
Why C# calls them methods
In languages built around classes, like C#, a reusable named block of code is called a method rather than a plain "function" — because it's always attached to a class, not floating free on its own. You've actually already called one: Console.WriteLine itself is a method belonging to the Console class.
Declaring a method looks like static int DoubleIt(int n) { ... } — the return type comes first (int, meaning this method hands back a whole number), then the name, then the parameter list in parentheses. static means, just like Main, that you can call this method directly from Main without first creating an object.
return n * 2; computes a value and immediately hands it back to whoever called the method, ending the method's execution at that point. C# convention capitalizes method names (DoubleIt, not doubleIt) — this is a stylistic convention (called PascalCase) rather than a hard rule, but following it makes your code look like idiomatic C#.
Loading editor...