Summary: in this tutorial, you’ll learn how to make your code reusable by using C# functions.
Introduction to the C# functions
Sometimes, you want to perform the same task multiple times in a program. To do so, you can copy and paste the code into various places. However, doing so makes the program very difficult to maintain.
In programming, we have the Don’t Repeat Yourself (DRY) principle. It means that if you find yourself writing the same statements over and over again, you can turn those statements into a function.
By definition, a function is a reusable named block of code that does one task.
For example, the following defines the SayHi()
function that outputs the "Hi"
message to the console:
void SayHi()
{
Console.WriteLine("Hi");
}
Code language: C# (cs)
In this function:
void
keyword indicates that theSayHi
function doesn’t return a value.- The
SayHi
identifier is the function name. And you should name the function as descriptive as possible. By convention, the function name should start with a verb (do something specific). - A function can have zero or more parameters specified in the parentheses that follow the function name. In this example, the
SayHi
function has no parameter. We’ll cover the parameters shortly. - The block that follows the parentheses is the function body. A function body contains one or more statements.
To use the SayHi()
function, you call it like this:
SayHi();
Code language: C# (cs)
Output:
Hi
Code language: C# (cs)
When encountering a function call, the compiler will execute the statement inside that function. In this example, it executes the statement that outputs the "Hi"
message.
And you can call the SayHi()
function as many times as you want like this:
void SayHi()
{
Console.WriteLine("Hi");
}
SayHi();
SayHi();
SayHi();
Code language: C# (cs)
Output:
Hi
Hi
Hi
Code language: C# (cs)
Passing information to functions
To say hi to someone, you can modify the SayHi()
function by adding the name
parameter like this:
void SayHi(string name)
{
Console.WriteLine($"Hi {name}");
}
Code language: C# (cs)
The name
is the input of the SayHi()
function. Technically speaking, the name is a parameter of the SayHi()
function.
Defining a parameter is like declaring a variable. And you can access the parameter like a variable inside the function.
When calling the SayHi()
function, you need to specify a value for the name
parameter as follows:
SayHi("John");
Code language: C# (cs)
Output:
Hi John
Code language: C# (cs)
Put it all together.
void SayHi(string name)
{
Console.WriteLine($"Hi {name}");
}
SayHi("John");
Code language: C# (cs)
Parameters vs. arguments
A function parameter is an identifier that you specify in the function definition while a function argument is a value that you pass to the function when calling it.
In the previous example, the name
is a parameter of the SayHi()
function. When calling the SayHi()
function, you pass the literal string "John"
to it. This string value is called an argument.
Sometimes, you’ll see the terms parameter and argument are used interchangeably. But it’s important to understand the difference between them.
Returning a value
The SayHi()
function doesn’t return any value. Therefore, you use the void
keyword. However, if a function returns a value, you need to specify the type of the return value instead.
For example, the following new SayHi()
function returns a string:
string SayHi(string name)
{
return $"Hi {name}";
}
Code language: C# (cs)
In this new SayHi()
function, we use the string
keyword as the return type of the function instead of void
. Also, we use the return
statement to return a string.
The following code calls the SayHi()
function, assigns the return value to the greeting
variable, and prints it out:
string SayHi(string name)
{
return $"Hi {name}";
}
string greeting = SayHi("John");
Console.WriteLine(greeting);
Code language: C# (cs)
Output:
Hi John
Code language: C# (cs)
The reason we return a string from the SayHi()
function instead of outputting it directly to the console is that we want to reuse the SayHi()
function in other applications such as web applications, not just console applications.
Documenting C# functions with XML comments
The following example defines the CalculateBMI()
function that calculates the body mass index based on the weight in kilograms and height in meters:
double CalculateBMI(double weight, double height)
{
return weight / (height * height);
}
Code language: C# (cs)
When calling the CalculateBMI()
function, the Visual Studio (or any code editor) shows the function header:
However, if you want it to show more information about the function, you can add comments to the function. like this:
/// <summary>
/// Calculate the body mass index (BMI) based on weight in kg and height in meter
/// </summary>
/// <param name="weight">
/// The weight in kilogram
/// </param>
/// <param name="height">
/// The height in meter
/// </param>
/// <returns>
/// The body mass index
/// </returns>
double CalculateBMI(double weight, double height)
{
return weight / (height * height);
}
Code language: C# (cs)
To create a comment section for a function, you enter three forward slashes (///
) right before the function header.
The comment of the CalculateBMI function has three main tags: summary
, param
, and returns
.
- The
summary
tag contains the function description - The
param
tag describes the parameters - The
returns
tag contains the information of the return value
C# function example
The following program calculates the BMI and displays the corresponding weight status:/
/// <summary>
/// Calculate the body mass index (BMI) based on weight in kg and height in meter
/// </summary>
/// <param name="weight">
/// The weight in kilogram
/// </param>
/// <param name="height">
/// The height in meter
/// </param>
/// <returns>
/// The body mass index
/// </returns>
double CalculateBMI(double weight, double height)
{
return weight / (height * height);
}
/// <summary>
/// Get the weight status based on the Body Mass Index (BMI)
/// </summary>
///<params name="bmi">
///The body mass index
///</params>
/// A text string that represents the weight status
///<returns>
///</returns>
string GetWeightStatus(double bmi)
{
string weightStatus = "";
switch (bmi)
{
case < 18.5:
weightStatus = "Underweight";
break;
case >= 18.5 and <= 24.9:
weightStatus = "Healthy Weight";
break;
case >= 25 and <= 29.9:
weightStatus = "Overweight";
break;
case > 30:
weightStatus = "Obesity";
break;
}
return weightStatus;
}
// main program
Console.WriteLine("Body Mass Index (BMI) Calculation");
Console.WriteLine("Enter a weight (kg):");
var weight = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Enter a height (m):");
var height = Convert.ToDouble(Console.ReadLine());
double bmi = CalculateBMI(weight, height);
string weightStatus = GetWeightStatus(bmi);
Console.WriteLine($"BMI: {bmi:0.#}");
Console.WriteLine($"Weight status:{ weightStatus}");
Code language: C# (cs)
How it works.
First, define the CalculateBMI()
function that returns the BMI based on weight and height:
/// <summary>
/// Calculate the body mass index (BMI) based on weight in kg and height in meter
/// </summary>
/// <param name="weight">
/// The weight in kilogram
/// </param>
/// <param name="height">
/// The height in meter
/// </param>
/// <returns>
/// The body mass index
/// </returns>
double CalculateBMI(double weight, double height)
{
return weight / (height * height);
}
Code language: C# (cs)
Next, define the GetWeightStatus()
function that returns the weight status based on a BMI:
/// <summary>
/// Get the weight status based on the Body Mass Index (BMI)
/// </summary>
///<params name="bmi">
///The body mass index
///</params>
/// A text string that represents the weight status
///<returns>
///</returns>
string GetWeightStatus(double bmi)
{
string weightStatus = "";
switch (bmi)
{
case < 18.5:
weightStatus = "Underweight";
break;
case >= 18.5 and <= 24.9:
weightStatus = "Healthy Weight";
break;
case >= 25 and <= 29.9:
weightStatus = "Overweight";
break;
case > 30:
weightStatus = "Obesity";
break;
}
return weightStatus;
}
Code language: C# (cs)
Then, prompt users to input the height and weight:
Console.WriteLine("Body Mass Index (BMI) Calculation");
Console.WriteLine("Enter a weight (kg):");
var weight = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Enter a height (m):");
var height = Convert.ToDouble(Console.ReadLine());
Code language: C# (cs)
After that, call the CalculateBMI()
and GetWeightStatus()
function to calculate the BMI and weight status:
double bmi = CalculateBMI(weight, height);
string weightStatus = GetWeightStatus(bmi);
Code language: C# (cs)
Finally, show the output:
Console.WriteLine($"BMI: {bmi:0.#}");
Console.WriteLine($"Weight status:{ weightStatus}");
Code language: C# (cs)
Summary
- A function is a reusable named block of code that does one task.
- A function can have zero or more parameters and an optional return value.
- Use the
return
statement to return a value from a function. - Use XML comments to document a function.