Methods and Functions
Methods and functions are important tools in programming that allow you to organize your code and make it reusable. In C#, a method is a code block that contains a series of statements. It can perform a specific task and can be called multiple times throughout the program.
Defining a Method
To define a method in C#, you use the static
keyword followed by the return type of the method. Here's an example:
1static void SayHello()
2{
3 Console.WriteLine("Hello, world!");
4}
In this example, SayHello
is the name of the method, and the void
keyword indicates that the method does not return a value.
Calling a Method
To call a method in C#, you simply write its name followed by parentheses. Here's an example:
1SayHello();
This will call the SayHello
method and execute the code inside it.
Method Parameters
Methods can also have parameters, which are values that are passed into the method. Parameters allow you to pass data from the calling code to the method. Here's an example:
1static int AddNumbers(int num1, int num2)
2{
3 return num1 + num2;
4}
In this example, AddNumbers
is a method that takes two parameters of type int
and returns their sum.
To call a method with parameters, you pass the values you want to use for the parameters inside the parentheses. Here's an example:
1int sum = AddNumbers(5, 7);
2Console.WriteLine("The sum is: " + sum);
This will call the AddNumbers
method with the values 5
and 7
and store the result in the sum
variable.
Methods and functions are essential in C# programming as they allow you to break down your code into logical units and make it easier to understand and maintain. They also promote code reusability, as you can call a method multiple times throughout your program. As you continue to learn C#, you'll explore more advanced concepts and techniques related to methods and functions.
Keep it up! You're one step closer to becoming a skilled C# programmer!
xxxxxxxxxx
using System;
class Program
{
// Define a method with void return type
static void SayHello()
{
Console.WriteLine("Hello, world!");
}
// Define a method with int return type
static int AddNumbers(int num1, int num2)
{
return num1 + num2;
}
static void Main()
{
// Call the SayHello method
SayHello();
// Call the AddNumbers method and store the result in a variable
int sum = AddNumbers(5, 7);
Console.WriteLine("The sum is: " + sum);
}
}