Methods in C# are blocks of code that perform a specific task or set of operations. They are declared within classes and can be called and executed when needed. Here’s an overview of methods in C#:
Syntax:
access-modifier return-type MethodName(ParameterList)
{
// Method body
// Code to be executed
// Optional return statement
}
Components of a method:
- Access modifier: Determines the accessibility of the method (e.g., public, private, protected, internal).
- Return type: Specifies the type of data the method returns. Use
void
if the method doesn’t return any value. - Method name: The unique identifier of the method.
- Parameter list: Optional input parameters that the method can accept. Parameters are declared with their data type and name.
- Method body: The block of code that contains the logic and operations to be executed.
Example of a method without a return value:
public void DisplayMessage(string message)
{
Console.WriteLine(message);
}
Example of a method with a return value:
public int AddNumbers(int a, int b)
{
int sum = a + b;
return sum;
}
Calling a method: To execute a method, you need to call it by its name followed by parentheses, optionally passing the required arguments:
int result = AddNumbers(5, 3);
DisplayMessage("Hello, World!");
Note that the called method should be accessible based on its access modifier (e.g., public methods can be called from anywhere).
Methods can also be overloaded, which means you can have multiple methods with the same name but different parameter lists. The compiler determines which overloaded method to call based on the arguments provided during the method call.
Methods are essential for organizing code into reusable and modular units, promoting code readability, and encapsulating logic and functionality within classes in C#.