Methods
In programming, methods are blocks of code that perform a specific task. They are like a reusable recipe that you can call whenever you need to perform that task.
In C#, you can define your own methods to encapsulate a set of instructions. Methods can take in parameters and return a value, or they can be void, meaning they don't return anything.
Here's a simple example that defines a method called Greet
and calls it:
1class Program
2{
3 static void Main(string[] args)
4 {
5 // Calling the Greet method
6 Greet();
7 }
8
9 // Define a method called Greet
10 static void Greet()
11 {
12 Console.WriteLine("Hello, world!");
13 }
14}
In this example, we defined a method called Greet
that doesn't take any parameters or return any value. We then called this method from the Main
method.
Methods can also take in parameters, which are values passed to the method when it's called. Here's an example:
1static void Sum(int a, int b)
2{
3 int result = a + b;
4 Console.WriteLine("The sum of " + a + " and " + b + " is " + result);
5}
6
7static void Main(string[] args)
8{
9 Sum(3, 5);
10}
In this example, we defined a method called Sum
that takes in two integers as parameters (a
and b
). The method calculates the sum of a
and b
and prints the result.
Methods are an essential part of organizing code and making it more modular. They allow you to break down complex tasks into smaller, more manageable parts. By using methods, you can write clean and reusable code.
xxxxxxxxxx
class Program
{
static void Main(string[] args)
{
// Calling the Greet method
Greet();
}
// Define a method called Greet
static void Greet()
{
Console.WriteLine("Hello, world!");
}
}