methods are blocks of code that perform a specific task. They are declared using the method
keyword, and you can call them to execute the code within them. Here's a simple tutorial on declaring and calling methods in C#:
Declaring a Method:
using System;class Program{// Method without parameters and return typestatic void SayHello(){Console.WriteLine("Hello, world!");}// Method with parameters and return typestatic int AddNumbers(int a, int b){return a + b;}// Method with parameters and no return type (void)static void PrintSum(int num1, int num2){int sum = num1 + num2;Console.WriteLine($"Sum: {sum}");}// Main method - entry point of the programstatic void Main(){// Calling the SayHello methodSayHello();// Calling the AddNumbers method and storing the resultint result = AddNumbers(5, 7);Console.WriteLine($"Sum: {result}");// Calling the PrintSum methodPrintSum(10, 20);}}
Explanation:
SayHello Method:
- Declared with the
static void
syntax, indicating it doesn't return a value. - Called in the
Main
method usingSayHello();
.
- Declared with the
AddNumbers Method:
- Declared with the
static int
syntax, indicating it returns an integer. - Takes two parameters (
a
andb
) and returns their sum. - Called in the
Main
method, and the result is printed.
- Declared with the
PrintSum Method:
- Declared with the
static void
syntax, indicating it doesn't return a value. - Takes two parameters (
num1
andnum2
), calculates their sum, and prints it. - Called in the
Main
method.
- Declared with the
Main Method:
- The entry point of the program.
- Calls the
SayHello
,AddNumbers
, andPrintSum
methods.
Output:
Hello, world!Sum: 12Sum: 30
This is a basic example, and you can expand on it by adding methods with different return types, more parameters, and additional logic. Methods are an essential part of organizing and reusing code in C#.