C# Methods
A method is a reusable block of code that performs a specific task, defined once and called whenever needed. Methods help organize code, avoid repetition, and make programs easier to understand.
A method has a name, a return type (or void if it returns nothing), and optionally, parameters that let you pass values into it.
static returnType MethodName(parameters) {
// code
return value;
}Defining and calling methods
A method is declared with an access modifier, return type, name, and parentheses, like `static int Add(int a, int b)`. It's called by using its name followed by arguments in parentheses.
Return values
A method with a non-void return type must use the `return` keyword to send a value back to the caller. void methods perform an action but don't return a value.
using System;
class Program {
static int Add(int a, int b) {
return a + b;
}
static void Main() {
int result = Add(3, 4);
Console.WriteLine(result);
}
}7Add() takes two ints, returns their sum, and Main() prints the result.
using System;
class Program {
static void Greet(string name) {
Console.WriteLine("Hello, " + name);
}
static void Main() {
Greet("Amy");
}
}Hello, AmyGreet() is a void method that performs an action without returning a value.
Key points
- Methods make code reusable and organized.
- A method's return type must match the type of the value it returns.
- void methods perform actions without returning a value.
- Methods are called by their name followed by parentheses with any arguments.
