In this tutorial, we will learn how to create and use methods in C#. We will define methods, invoke them, and understand their role in programming.
At the end of this tutorial, you should be able to:
This tutorial assumes that you have a basic understanding of C# syntax.
In C#, methods are blocks of code that perform specific tasks. They are defined inside a class or struct, and they are used to organize code into manageable pieces. A method can also return a value and take parameters.
A method is defined with the following syntax:
access_modifier return_type method_name( parameters )
{
// method body
}
Here's a simple example:
public int Add(int a, int b)
{
return a + b;
}
In this example, public
is the access modifier, int
is the return type, Add
is the method name, and (int a, int b)
are the parameters.
Once a method is defined, it can be called from another method, constructor, or property. Here's an example:
int result = Add(5, 10);
In this example, Add
method is being called with two arguments, 5
and 10
. The result of the operation is stored in the result
variable.
class Program
{
static void Main(string[] args)
{
int result = Add(5, 10);
Console.WriteLine(result); // Outputs: 15
}
static int Add(int a, int b)
{
return a + b; // Returns the sum of a and b
}
}
class Program
{
static void Main(string[] args)
{
SayHello("John"); // Outputs: Hello, John!
}
static void SayHello(string name)
{
Console.WriteLine("Hello, " + name + "!");
}
}
In this tutorial, we've covered how to create and use methods in C#. We learned how to define a method, call it, and understand its purpose in programming.
Next, you might want to learn about more advanced topics related to methods, such as method overloading, optional parameters, and recursion.
Write a method that takes two integers as parameters and returns their product.
static int Multiply(int a, int b)
{
return a * b;
}
Write a method that takes a string as a parameter and prints it to the console.
static void PrintMessage(string message)
{
Console.WriteLine(message);
}
Write a method that takes no parameters and returns a random number.
static int GenerateRandomNumber()
{
Random random = new Random();
return random.Next();
}
Remember to practice regularly to enhance your understanding of methods in C#.