Methods and functions
In C#, methods and functions are used to encapsulate a block of code that performs a specific task. They provide a way to organize and reuse code by defining a set of instructions that can be called and executed from different parts of a program. Here’s an overview of methods and functions in C#:
- Method Declaration:
A method is declared with a name, optional parameters, return type, and a block of code.
Example
// Method with no parameters and no return value
void PrintHello()
{
Console.WriteLine(“Hello!”);
}
// Method with parameters and a return value
int AddNumbers(int a, int b)
{
return a + b;
}
- Method Parameters:
Parameters are placeholders that allow you to pass data into a method.
Parameters can be of any data type, and multiple parameters can be separated by commas.
Example
void Greet(string name)
{
Console.WriteLine(“Hello, ” + name + “!”);
}
void Multiply(int a, int b)
{
int result = a * b;
Console.WriteLine(“Result: ” + result);
}
- Return Type:
The return type specifies the type of value that a method returns after executing its code.
Use the void keyword for methods that do not return a value.
Example:
int GetSum(int a, int b)
{
return a + b;
}
void PrintMessage(string message)
{
Console.WriteLine(message);
}
- Calling Methods:
To execute a method, you need to call it by its name, passing any required arguments.
Example:
PrintHello(); // Calling a method with no parameters
Greet(“John”); // Calling a method with a parameter
Multiply(3, 4); // Calling a method with multiple parameters
int sum = GetSum(2, 3); // Calling a method with a return value
- Method Overloading:
Method overloading allows you to define multiple methods with the same name but different parameter lists.
The compiler determines which method to call based on the arguments provided.
Example
void PrintNumber(int number)
{
Console.WriteLine(“Number: ” + number);
}
void PrintNumber(double number)
{
Console.WriteLine(“Number: ” + number);
}
- Main Method:
The Main method is the entry point of a C# program and is required for execution.
It serves as the starting point from which the program’s execution begins.
Example:
static void Main(string[] args)
{
// Code to execute when the program starts
}
Methods and functions play a crucial role in organizing and structuring code in C#. They allow you to break down complex tasks into smaller, manageable parts and promote code reuse and maintainability.