In C#, a function (also called a method) is a block of code that performs a specific task. You can define a function to perform a specific operation and then call it to use that functionality in your program. Functions and methods help organize your code and avoid repetition.
A simple function looks like this:
returnType FunctionName(parameters) {
// function body
return value;
}
- `returnType`: The type of data that the function will return. If the function doesn't return any value, you use `void` as the return type. - `FunctionName`: The name of the function. - `parameters`: The input values that the function accepts (optional). - `return`: The value that the function returns (if any).
int AddNumbers(int a, int b) {
return a + b;
}
This function takes two integer parameters (`a` and `b`) and returns their sum as an integer.
Once a function is defined, you can call it using its name and passing in the required parameters:
int result = AddNumbers(5, 10); // result is 15
Use the input fields below to input two numbers and see the result of the sum by calling the `AddNumbers` function:
Result of Addition:
0
1. What is the purpose of a function in C#?
2. What keyword is used to define a function that does not return any value?
3. Which of the following is the correct syntax for calling the function `AddNumbers(5, 10)`?
4. How do you specify the return type of a function in C#?
5. What does the following function declaration do?
int MultiplyNumbers(int a, int b) { return a * b; }