What are Functions?
A function is a named block of code that performs a specific task. You write it once and run it whenever you need it.
Functions break big problems into smaller, manageable pieces and save you from repeating the same code.
In C#, functions are officially called methods. You'll see me use both terms.
Syntax
In C#, functions have the following structure:
static returnType FunctionName(inputType inputName)
{
// code
return valueToReturn;
}
static: Lets you call the function directly fromMainwithout creating an object. We'll explain this laterreturnType: The type of value the function gives back. Usevoidif it gives back nothingFunctionName: The function's name, written inPascalCaseinputType inputName: A parameter: an input the function needs. Leave the parentheses empty if it needs nonereturn: Sends a value back as the function's output and ends the function
Analogy Time
A function is like packing a box:
C# looks at your function body and goes "Ok cool" lets shove this code in a box to use for later. What's the label of the box? The label of your box is the FunctionName!
Why doesn't C# run the function right away? Cause you didn't tell it to. To get access to what’s in the box, you gotta “open” it.
How do u open it tho? To open the box, you need to give it parameters!! Think of this like the "keys" to open the box.
Example 1. Say Hello Sometime
Write a function that prints "Hello"
static void SayHello()
{
Console.WriteLine("Hello");
}
This function:
- Takes no inputs, so the parentheses are empty
- Returns nothing, so the return type is
void
Call it by writing its name followed by parentheses (no "keys" this time, so we pass it nothing)
SayHello();
Example 2. Ice Cream
Functions typically take arguments (special name for an input variable). SOOO, write a function that serves ice cream with a given number of scoops and flavour.
static void GetIceCream(int scoops, string flavour) // scoops & flavour are "arguments"
{
Console.WriteLine($"Here is {scoops} scoop(s) of {flavour} 🍦");
}
To serve two customers:
GetIceCream(2, "Rocky Road");
GetIceCream(1, "Charlie Brownie");
The values you pass in (2, "Rocky Road") are called arguments.