In this article I’ll be explaining C# methods (AKA functions). A method is a set of code that is combined into a packet that helps organize the code in a way that can be played/ run multiple times. A good way to think of a method is like the process of tying a shoe – each time you tie a shoe you’re repeating the same set of steps, which are therefore like a repeatable packet of instructions that you follow (a method). A use of a method is a calculator program that solves the formula for a rectangle’s area (as an example) – take input for the variables in the formula, replace the variables with the input, solve the formula in order, and display the result – which can be combined into a method called ‘rectangle_area’, that when called/ referenced in the code tells the program to follow those instructions.
- Using a method for a practical purpose (1st program example)
- Passing parameters and returning a value (2nd program example)
- Another example of passing a parameter to a method (Third program)
- Summary
- Conclusion
For this article, I’ll be using Visual Studio 2019 but, Code::Blocks, Visual Studio Code, or something similar may work just as well. Also, before we start, in case you want to learn more about C#, this wiki may be useful.
First let’s learn about the static void Main
method, which is where the code that we want to run goes, it’s almost like a manager of a store or business but for our program because, any code that we want to be run/ processed has to be written or referenced in here. Also like a manager, the Main method can have helpers to accomplish a goal — the methods that we create, and these can be made in the Main method or outside it, the later of which can help keep the static void Main
method more organized by reducing the code in it and still providing the necessary instructions to run the program (as long as the method stays inside class Program
and is called/ referenced in the Main
method , or a properly referenced class — which is a topic that we’ll learn in a future article). The following example defines the method outside static void Main
.

Next let’s learn about what it means for a method to be public
or private
because, this an important characteristic of C# methods. Public
or private
is a way of pre-defining how the method (or other aspect of code) can be used through out the program — public
methods and their contents can be used/ accessed through out the program easier, while private
is hidden. The following two examples show to ways to make both.
public static void method_name()
{
//code
}
private static void method_name()
{
//code
}
Another aspect of a method shown in the code examples above is the void
term which tells the program that that specific method doesn’t return a value — something that a later example will show how to do.
Side note: the following examples will show how to make a method but, they’ll also show how to use methods that are part C#, such as Console.ReadLine()
and int32.Parse()
that are part of the System
namespace
.
First program: Using a method to solve a formula
Using the calculator program example mentioned earlier, let’s say we want our method to be for finding the combined area of two rectangular rooms.
The Main method:
using System;
namespace Blog_Function_Prog
{
class Program
{
static void Main (string[] args)//The main method/ function in the program
{
Area_calc();//Telling the program to run the method
}
//Make the method
}
}
Making the method:
public static void Area_calc()//The newly created method
{
Console.Write("Enter the first length: ");
string input_length1 = Console.ReadLine();
int length1 = Int32.Parse(input_length1);
Console.Write("Enter the first width: ");
string input_width1 = Console.ReadLine();
int width1 = Int32.Parse(input_width1);
//Checking
Console.WriteLine("Inputed length: " + input_length1);
Console.WriteLine("Inputed width: " + input_width1);
int area = length1 * width1;
Console.WriteLine("First area: " + area);
Console.WriteLine("\n");
//-----------------
Console.Write("Enter the second length: ");
string input_length2 = Console.ReadLine();
int length2 = Int32.Parse(input_length2);
Console.Write("Enter the second width: ");
string input_width2 = Console.ReadLine();
int width2 = Int32.Parse(input_width2);
//Checking
Console.WriteLine("Inputed length: " + input_length2);
Console.WriteLine("Inputed width: " + input_width2);
int area2 = length2 * width2;
Console.WriteLine("Second area: " + area2);
Console.WriteLine("\n");
int total = area + area2;
Console.WriteLine("Total area: " + total);
Console.WriteLine("\n");
}
Output:
Enter the first length: 3
Enter the first Width: 12
Inputed length: 3
Inputed width: 12
First area: 36
Enter the second length: 12
Enter the second Width: 4
Inputed length: 12
Inputed width: 4
Second area: 48
Total area: 84
The way this program works is:
The
method calls static void Main
Area_calc
(the method that we made for this program), and this runs the instructions to display prompts on the screen, gather the length and width values, process those values, and then display the area results. To be able to process the numbers that are typed into the console (the length and width values for the imaginary rooms), in Area_calc
, we make a string variable called input_length1
and set it to the result of Cosole.ReadLine()
method. After that, we make a new variable to store those numbers in their integer format, and this is because even though the numbers for the length and width are integers, after being processed through Console.ReadLine()
, they’re stored as strings which can’t be processed through addition or subtraction like integers. To convert the numbers from strings to integers, we use the Int32.Parse()
method. To double check our values, we can display the values that are now stored as the first length and width to the console. Now that we have the length and width values for one of the rooms, on the next line we make a variable area
and set it the value of the area of the first room.
Then to get the length and width values for the second room, we basically copy the process we used for the first room, changing the variables and prompt messages as needed.
After the program has gathered the length and width values for both rooms, and calculated the two areas, we can combine those two area values to get the total
, which can then be displayed on the screen.
Second program: Passing parameters and returning a value
This next example will show how to further use a method by passing parameters (values) to it, and how to make the method return a value.
The Main method and the first part of the program:
using System;
namespace Blog_Method_Prog
{
class Program
{
static void Main(string[] args)//The main method/ function in the program
{
int area;
Console.Write("Enter the first length: ");
string input_length1 = Console.ReadLine();
int length1 = Int32.Parse(input_length1);
Console.Write("Enter the first Width: ");
string input_width1 = Console.ReadLine();
int width1 = Int32.Parse(input_width1);
//Checking
Console.WriteLine("Inputed length: " + input_length1);
Console.WriteLine("Inputed width: " + input_width1);
area = Area_calc_v2(length1, width1);//Setting the area integer to the value returned by the function we made, after passing two parameters to it
Console.WriteLine("Total area: " + area + "\n");
Console.Write("Enter the second length: ");
string input_length2 = Console.ReadLine();
int length2 = Int32.Parse(input_length2);
Console.Write("Enter the second Width: ");
string input_width2 = Console.ReadLine();
int width2 = Int32.Parse(input_width2);
//Checking
Console.WriteLine("Inputed length: " + input_length2);
Console.WriteLine("Inputed width: " + input_width2);
area += Area_calc_v2(length2, width2);//Running the method again with two passed parameters
Console.WriteLine("Total area: " + area + "\n");
}
//Method goes here
}
}
The method:
static int Area_calc_v2(int length, int width)//The Method
{
return length * width;
}
Output:
Enter the first length: 2
Enter the first Width: 44
Inputed length: 2
Inputed width: 44
Total area: 88
Enter the second length: 4
Enter the second Width: 18
Inputed length: 4
Inputed width: 18
Total area: 160
The way this version works is:
Instead of using the method to gather and calculate the length and width values, the values are gathered and processed by the code in the Main
method and then passed — or you could say given — to the method we’ve made, that then processes the area and returns/ packages the result making it ready to use by the Main
method.
To be able to pass parameters to our method, first we have to list temporary integer variables (int
length
and int
width
) that are like front desk workers in a business for our method in that they take the info that we want to give our method to process (the integer values of the length and width of the room), and they make sure the method can read/ understand what they are, which is done by defining the variables as int
.
Then to pass the parameters to the method, we call the method like normal, and then add the variables storing the length and width values (length1 and width1 corresponding to the first room) in our method’s parenthesis.
As shown in the output, this version doesn’t write out the individual areas of the two rooms but instead the “Total area”, and this is because that would’ve required an additional variable to store the area of the second room — to avoid overwriting the area value of the first room stored in area
after the fist room.
A somewhat greater difference from the first program: the method in this program simply multiplies the length and width values that are passed to it, and then returns the result of that, not storing the value in a variable. Like mentioned earlier, returning a value is like packaging a set of data so that the rest of the program can process it. This returning of the result is important for making this version of the program work because, let’s say the method for this example was instead:
public static void Area_calc(int length, int width)//The function
{
int temp_area = length * width;
Console.WriteLine("Area: " + temp_area);
Console.WriteLine("\n");
}
This would write out to the correct value to the console but, the value of temp_area
(a variable for storing the area in this mini example) wouldn’t be easily accessible to the rest of the program — the part in the Main
method (unless we possibly returned that variable, or used global variables — but that’s for another example), and therefore that value wouldn’t be able to be added to or subtracted to, or written out to the screen through a Console.WriteLine()
through the Main
method. Because, temp_area isn’t defined in a way that this method and the code the Main
method would be able to ‘see’ it, using temp_area in the rest of the program would be like saying phones + 1 out of context to your friend you were counting phones with in a store last week (as a random example). So, this is why we return
the value of the multiplication of the length and width that we passed to our method — it makes it possible to take the result of what the method processed and use that elsewhere, instead of just writing it out to the screen (like the example above). You may wonder why not store the are in a variable like in this mini example above, and then return that instead of simply returning the result of the calculation, like our actual code, and this is because, returning the result of the calculation is simpler.
Third program: Another example of passing a parameter to a method
Now, we’ll make a program that uses a method to calculate the last digit of pi cause who needs a supercomputer for that, 3.1415… it should be simple right? Actually, no. Let’s leave that to the supercomputer for now.
Our next program will show another example of passing a parameter to a method, this time to move the x and y coordinates of an imaginary character similar to how a character’s position in a game may be changed. For this program, our character’s position will update when w, a, s, or d is typed into the console and the Enter/ Return key is pressed.
The Main method and the first part of the program
using System;
namespace Character_movement
{
class Program
{
public static string input;
public static int x = 0, y = 0; //variables for x and y position of the character
static void Main(string[] args)
{
Console.WriteLine("The character is at x: " + x + " " + "y: " + y);
Console.WriteLine("Press w, a, s, d to move the character, and then press enter");
while (true)//Keeps the program running so that character can be moved as much as desired
{
input = Console.ReadLine();
position_check(input);
}
}
//Method goes here
}
}
Making the method:
public static void position_check(string letter)// Our method
{
//Checking for change in x
if (letter == "a")
{
x -= 1;
Console.WriteLine("The character is at x: " + x + " " + "y: " + y);
}
else if (letter == "d")
{
x += 1;
Console.WriteLine("The character is at x: " + x + " " + "y: " + y);
}
//Checking for change in y
else if (letter == "w")
{
y += 1;
Console.WriteLine("The character is at x: " + x + " " + "y: " + y);
}
else if (letter == "s")
{
y -= 1;
Console.WriteLine("The character is at x: " + x + " " + "y: " + y);
}
else// Checking for an unexpected input
{
Console.WriteLine("I didn't get that, the character is at x: " + x + " " + "y: " + y);
}
}
The character is at x: 0 y: 0
Press w, a, s, d to move the character, and then press enter
w
The character is at x: 0 y: 1
d
The character is at x: 1 y: 1
d
The character is at x: 2 y: 1
a
The character is at x: 1 y: 1
s
The character is at x: 1 y: 0
The way this program works is:
First we make our variables – a string
input
for storing the letter that’s typed into the console, and then two integers x
and y
for storing the position of our imaginary character. These variables are defined as Global variables (outside the Main
method but still in the Program
class
) because, this gives us the ability to use these variables through out the program – in the Main
method and in the dedicated method we’ll create later on in the code. Then, the first thing that we do in the Main
method is display the initial x
and y
values of our character’s position, along with a prompt saying which letters to type to move the character. To keep the program running like an actual game would (instead of just ending when the x or y position got to some arbitrary value), we make a while
loop and set its condition tor true, which makes it run forever (as long as true
is true
, it runs). Inside the while
loop, we set the string
input
variable we made earlier to the value of what is read in by Console.ReadLine
. Then we pass the value now stored in the input
string to our method position check
.
Our position_check
uses an if statement, multiple else ifs, and an else statement to determine the character that was typed into the console and passed to it. The value of the x
or y
variables is changed based on which of the if/ else if checks gets their condition met based on the letter that was typed into the console, and then the new value of both of the variables is displayed to the console. Note that though the value of the input
string
is passed to our method as a parameter, our method could check its value without it being passed — by replacing the condition of the if/ else if statements to check the value of input
. This second way of checking input’s value is slightly simpler but, it’s a good opportunity to practice passing parameters to a method, and the first adds little extra complexity.
A basic explanation of the if, else if, and the else statement in our program:
- The first if/ else ifs check what type of letter was typed, and depending on the letter, adjust the variables and display the updated x and y position of the character
- The else statement is a back up check that you could say “catches all the other possible inputs” and displays a message that the computer/ program didn’t understand the input.
Note: when running this program, sometimes the program is isn’t quick enough to register that a letter has been typed and the Enter/ Return key has been pressed, and this makes the condition of the last else statement in our program become true
Errors that you may encounter with methods:
- Unable to pass a parameter to the method (red line under the parameter when trying to call the method): You may be getting and error with this because, the definition of the method doesn’t initialize the parameter, and this would be like asking someone if the saw something without telling them to look for it in the first place.
- Error passing two parameters to method (red line under the parameters when trying to call the method): You may be getting and error with this because, like the previous potential error, the method wouldn’t be ‘prepared’ so to speak to process the two parameters, and to prevent this all you have to do is put a comma in-between the parameters when initializing them in the method’s definition (also remember to include the comma when calling/ running the method).
- Error when attempting to use a variable defined inside the method in the rest of the program (red line under the variable): To understand why you’d be getting this type of error, consider the process of tying a shoe again; the color of the shoe can be represented using a term (variable) ‘Shoe_color’ which, when used in the context of shoes makes sense, but say that term in the context of cooking (just a random situation), and it wouldn’t really make sense. So, for a program to fully understand how to process the info you give — such as the variables — you have to define them in the method where they’ll be used, or right before the
Main
method as a global variable; there’s also likely a way to reference variables from another class using inheritance but, that’s a more complicated topic for another article, and we’re not using multiple classes in the programs for our examples here.
Summary
In this article we learned about C# methods and went through a few examples of how to use them including a way to use a method to calculate the area of two rooms, how to use a method to calculate the area of two rooms while passing it parameters, and how to use a method to update the x and y position of a character. Our first program is a very basic method example that has the method “do all the work” of the program, and only get called from the Main method. The second program was a sort of flip of the first in how much code the Main method and our custom method had, and we learned that to pass parameters to a method has to be defined with the type of parameter it will receive, and that each parameter parameter has to have a comma in between it and the next – when defining and calling the method. the program also helped us learn how to return a value from a method, making that value able to be used by other parts of the code. Our third program helped us practice passing a parameter to our method, making global variables, using multiple if/ else if/ else statements, and using a while loop, all to make program where our method determines the letter that was typed into the console to move the x and y coordinates of an imaginary character. Through out our three programs, we also learned how to use the Int32.Parse()
and Console.ReadLine
() methods that are included in the C# language as part of the System
namespace
.
Areas for improvement:
- In the third program: we could’ve used
System.Windows.Input
instead of Console.ReadLine() to register whether a key is pressed, which would make it so that the Enter/ Return keys doesn’t have to be pressed to ‘submit’ the character movement. Though, we used Console.ReadLine() because, it could be easier to set up and understand.
Conclusion
Thank you for reading this article on C# methods, I hope you enjoyed and learned from it, and if you did, our C#, C++, C, or other archives may interest you. If you have any questions or comments, feel free to post them below, and we’ll do our best to reply.