Methods
Explore how to define and use methods in C# within a program. Understand method syntax, calling methods from Main, void vs. return types, and returning values to reuse code effectively.
We'll cover the following...
Create methods
A variable is a named area of memory that holds a value of some type. C# methods (often referred to as C# functions) are similar, but instead of holding a value, methods are named blocks of instructions.
The basic syntax for creating a method is as follows:
[modifiers] return_type method_name([parameters]){// Method body}
modifiers: Optional keywords (likestaticorpublic) that define accessibility and behavior.return_type: The data type of the value the method sends back (orvoidif it returns nothing).method_name: The identifier used to call the method.parameters: Optional input variables defined within parentheses.Method body: The code block enclosed in curly braces
{}.
Beyond using the Console.WriteLine() method to print text, we have already used one method that serves as the entry point in structured .NET programs:
static void Main(string[] args){}
Line 1: Defines the method signature.
static: A modifier indicating the method belongs to the class itself, not an instance.void: The return type, indicating this method does not return a value.Main: The specific name required for the program's entry point.string[] args: A parameter accepting an array of strings (command-line arguments).
Lines 2–3: The curly braces define the body where the method's instructions reside.
Note: In C# 14, modern project templates often use top-level statements. This feature allows us to write code without explicitly defining the class Program or Main method, as the compiler generates them automatically. However, understanding the explicit Main method structure remains important for understanding how C# applications operate.
Let’s create two methods that produce a greeting in English and Spanish.
Lines 11–14: Defines
SayHelloEnglish. It isstatic(matchingMain), has avoidreturn type, and takes no parameters (empty parentheses).Line 13: The instruction to print “Hello!” to the console.
Lines 16–19: Defines
SayHelloSpanishwith similar structure but different internal logic.
Both methods are defined within the Program class, and they are static. This means that we do not have to create an instance of the Program class to use them. Their return type is void, meaning they perform actions without returning a value.
Additionally, neither method has any parameters, so there are empty parentheses after the method name.
If we run the program now, nothing happens because the Main() method is empty. We created two methods, but they are not used yet.
Call methods
To use our two methods, SayHelloEnglish() and SayHelloSpanish(), we need to call them from the Main() method.
To call a method, we type its name and provide the required parameters inside the parentheses. In our case, we only type the names followed by empty parentheses.
Line 9: Calls
SayHelloEnglish(). Program execution jumps to line 13, runs the code there, and returns to line 10.Line 10: Calls
SayHelloSpanish(). Program execution jumps to line 18, runs the code there, and returns to finish theMainmethod.
Methods are essential for code reuse. Instead of typing the same functionality repeatedly, we can create a suitable method and use it whenever we need it.
Return values
A method can return a value. In the example above, two methods were defined with the type void. Methods of this type do not return any value; they perform actions and exit.
Methods with a return type other than void must output a matching value using the return statement.
For example, we need a method that calculates the square of a number. We can start creating a method with the following definition:
static int GetSquare(int number){// Logic}
static int: The method returns data of typeint.(int number): The method defines a parameter namednumberof typeint.
So, our method’s name is GetSquare(). Let’s implement this method now.
Line 13: Calculates the square of
numberand stores it in the variableresult.Line 14: The
returnkeyword sends the value ofresultback to the code that called the method.
The GetSquare() method has an int return type, which means the method must return an int value. In the method body, we return the result variable, which is of type int. If we tried to return a string, the compiler would generate an error.
After the return keyword, we can use expressions directly. For instance, we could make the method shorter by doing the following:
static int GetSquare(int number){return number * number;}
Line 3: Evaluates the expression
number * numberand returns the result immediately, without needing a temporary variable.
A value returned from the method can be assigned to a variable or used in some other way within the program. Let’s complete our program.
Line 9: Calls
GetSquarewith the argument5. The returned value (25) is assigned to the integer variablesquareOfFive.Line 10: Displays the result using string interpolation.
The return keyword outputs a value and immediately terminates method execution. In void methods, the return keyword can force an early exit.
Line 9: Calls
PrintAgewith an invalid age (-1).Line 14: Checks if
ageis less than 0.Line 16: Executes
return. Since the method isvoid, no value is provided. The method stops executing immediately, skipping line 19.