Curriculum
Functions, also known as methods, in C# are blocks of code that perform a specific task and can be called from other parts of the program. Functions can take zero or more parameters and can return a value or not. The basic syntax for defining a function in C# is:
access_modifier return_type function_name(parameters) { // Function body return value; }
Here is a breakdown of the parts of a function definition:
access_modifier
: Determines the accessibility of the function. It can be public
, private
, protected
, or internal
.return_type
: Specifies the type of value that the function returns. It can be a built-in type, a custom class, or void
if the function does not return a value.function_name
: Specifies the name of the function.parameters
: Specifies the input values to the function. It can be zero or more parameters separated by commas, each with a type and a name.function_body
: The code that performs the task of the function.return value
: Specifies the value that the function returns.Here is an example of a simple function that takes two integers as input and returns their sum:
public int Add(int a, int b) { int sum = a + b; return sum; }
In this example, the Add
function takes two integer parameters a
and b
, adds them together, and returns the result.
Functions can also have default parameter values and can be overloaded, meaning that multiple functions with the same name but different parameter lists can exist. Here is an example of an overloaded function:
public int Multiply(int a, int b) { return a * b; } public double Multiply(double a, double b) { return a * b; }
In this example, there are two Multiply
functions: one that takes two integers and one that takes two doubles. The functions have the same name but different parameter lists and return types.
Functions can also be recursive, meaning that a function can call itself. Here is an example of a recursive function that calculates the factorial of a number:
public int Factorial(int n) { if (n <= 1) { return 1; } else { return n * Factorial(n - 1); } }
In this example, the Factorial
function checks if the input number n
is less than or equal to 1. If it is, it returns 1. Otherwise, it multiplies n
by the result of calling Factorial
with n-1
as the input.
Overall, functions are a fundamental building block of any program in C#, allowing code to be organized into modular, reusable blocks that can be easily called and combined to perform complex tasks.