Search⌘ K
AI Features

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
}
General syntax for defining a method
  • modifiers: Optional keywords (like static or public) that define accessibility and behavior.

  • return_type: The data type of the value the method sends back (or void if 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)
{
}
The explicit Main method definition
  • 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.

C# 14.0
using System;
namespace Methods
{
class Program
{
static void Main(string[] args)
{
}
static void SayHelloEnglish()
{
Console.WriteLine("Hello!");
}
static void SayHelloSpanish()
{
Console.WriteLine("Hola!");
}
}
}
  • Lines 11–14: Defines SayHelloEnglish. It is static (matching Main), has a void return type, and takes no parameters (empty parentheses).

  • Line 13: The instruction to print “Hello!” to the console.

  • Lines 16–19: Defines SayHelloSpanish with 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.

C# 14.0
using System;
namespace Methods
{
class Program
{
static void Main(string[] args)
{
SayHelloEnglish();
SayHelloSpanish();
}
static void SayHelloEnglish()
{
Console.WriteLine("Hello!");
}
static void SayHelloSpanish()
{
Console.WriteLine("Hola!");
}
}
}
  • 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 the Main method.

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
}
Method signature with an integer return type
  • static int: The method returns data of type int.

  • (int number): The method defines a parameter named number of type int.

So, our method’s name is GetSquare(). Let’s implement this method now.

C# 14.0
using System;
namespace Methods
{
class Program
{
static void Main(string[] args)
{
}
static int GetSquare(int number)
{
int result = number * number;
return result;
}
}
}
  • Line 13: Calculates the square of number and stores it in the variable result.

  • Line 14: The return keyword sends the value of result back 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;
}
Simplifying the return statement
  • Line 3: Evaluates the expression number * number and 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.

C# 14.0
using System;
namespace Methods
{
class Program
{
static void Main(string[] args)
{
int squareOfFive = GetSquare(5);
Console.WriteLine($"Square of 5 is {squareOfFive}");
}
static int GetSquare(int number)
{
return number * number;
}
}
}
  • Line 9: Calls GetSquare with the argument 5. The returned value (25) is assigned to the integer variable squareOfFive.

  • 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.

C# 14.0
using System;
namespace Methods
{
class Program
{
static void Main(string[] args)
{
PrintAge(-1);
}
static void PrintAge(int age)
{
if (age < 0)
{
return;
}
Console.WriteLine($"Your age is {age}.");
}
}
}
  • Line 9: Calls PrintAge with an invalid age (-1).

  • Line 14: Checks if age is less than 0.

  • Line 16: Executes return. Since the method is void, no value is provided. The method stops executing immediately, skipping line 19.