Lesson: C# Functions and Methods

What are Functions and Methods in C#?

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.

Function Syntax

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).

Example of a Simple Function

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.

Calling a Function

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

Interactive Example: Call a Function

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

Quiz: Test Your Knowledge on C# Functions and Methods

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; }