Functions
A function is a block of code that performs a specific task and can be called from other parts of the program. In C#, functions are also called methods.
Function structure
A function structure includes several key elements:
- Return type - indicates the type of data the method returns. If the method returns nothing, the keyword
voidis used. - Method name - the identifier by which the method will be called.
- Parameter list - in parentheses, the method's input parameters are listed (if any), each with a type and a name.
- Method body - a block of code enclosed in curly braces {}, containing the method implementation.
Line 1, Char 1
Function with no return value and no parameters
Used simply as a reusable block of code.
Line 1, Char 1
Function with no return value and one parameter
For example, a function accepts a
name parameter and inserts it into a greeting string Line 1, Char 1
Function with a return value and no parameters
For example, a function returns a greeting string
Line 1, Char 1
Function with a return value and one parameter
For example, a function returns a greeting string in which
name is inserted from the parameter Line 1, Char 1
Function with a return value and multiple parameters
Functions can accept multiple parameters but return only one value (or nothing). For example, a function accepts 2 numbers as parameters and returns their sum
Line 1, Char 1
Exercises
- Write a function with no return value and no parameters that always prints your birth year to the console.
Line 1, Char 1
- Write a function with no parameters that always returns your birth year.
Line 1, Char 1
- Write a function that accepts a birth year, calculates age, and returns it. Call the function with your birth year and with another person's birth year.
Line 1, Char 1
- Write a function that accepts a name and birth year, calculates age, and returns a string in the format
Name: {name}, age: {age}
Line 1, Char 1