Methods
Declare a local function or static method
Top-level programs can use local functions. Classes use methods.
int Add(int a, int b) => a + b;
Console.WriteLine(Add(2, 3));
Return values and void
void methods perform work without returning data.
void Greet(string name)
{
Console.WriteLine($"Hello, {name}");
}
Greet("World");
Optional parameters
Defaults make some arguments optional at the call site.
void Ping(string host = "localhost") => Console.WriteLine(host);
Ping();
Ping("example.com");
Method habits
- Use verbs for method names:
CalculateTotal - Keep methods focused on one job
- Prefer returning values over printing inside helpers
- Out and ref parameters exist; beginners can usually avoid them
Comments
One comment per signed-in account. Comments are saved with this page’s URL.