I'm sure you have used methods or functions if you have ever written a computer program in any object-oriented programming language. In this article, we will learn everything about methods in C# programming language. We will learn how to define a method in C#, what method is used for, how to call a method, and what different keywords are used with a method in C#.
Classes and objects are the fundamental concepts in C# programming. A class is a blueprint of objects. For example, a Car class represents a car object in the real world. A car in the real world has some properties, and it does something. For example, a car has four wheels, a steering wheel, seats, color, brand, type, and so on. These are various properties of a car. A car also starts, stops, and drives. These are some of the activities of a car.
We use classes to represent a car in an object-oriented programming language such as C#. A class name, Car, represents a car object. The car can have properties such as a Blue Toyota Carolla or a Red Ford F-150. These are two different models from two different manufacturers. While their color and manufacturer may differ, both of these cars start, stop, and drive. These actions in the object-oriented programming world are represented in methods. The Car class has three methods - Start(), Stop(), and Drive().
What is a method in C#?
In C#, a method is a code block that contains a series of code statements. A method is used to perform a specific task and can be called from other parts of the program. Methods can also accept parameters, which are used to pass data into the method, and can return a value or a reference to an object. Methods are declared using the keyword "void" or a specific data type, such as "int" or "string".
A method is a code block that contains a series of statements.
A method is a code block that contains a series of statements. It can group related code, reuse code, and control program flow.
A method helps to reuse code.
Methods are the building blocks of C# and are very useful for structuring your code. They can be used to repeat a task, for example, in looping through a collection of items or repeating a task until a condition is met. Methods also reduce the code size.
To execute the method, its name is written, followed by brackets ().
In C#, methods are not executed automatically. They must be called by another method or function. This means that if you write a method and don't call it anywhere else in your program, then nothing will happen when your program runs.
Methods can also be called other methods.
The Main method calls the Add method when it starts up and displays its result on the screen (e.g., "10 plus 20 equals 30").
The Add2() method calls the Add1() method to add two numbers together before displaying their sum (e.g., "2 plus 3 equals 5").
Each method must have its own unique name.
Each method must have its own unique name. For example, if you have a method called GetData() in one class and another with a method with the same name, it will cause an error.
The names of methods should be descriptive and PascalCase. We recommend using nouns when naming your methods because they're more commonly used than verbs when describing actions or tasks that can be performed by something (a person or object).
Methods provide a way to keep things organized in your program.
Methods are a way to keep things organized in your program. They allow you to reuse code and make it more readable.
In the following example, we have a " add " method that adds two numbers together. This function can be used anywhere in our program by calling it with parameters (5 and 10).
C# Method Examples
Let's look at some of the examples of C# methods.
Here is a method that converts a string value to an array of integers. You can take this method, define in any class, make it available publicly, and call it from any other classes to convert a string to an int array.
private int ToIntArray(string s)
int o = s.Length;
int iArray = new int[o];
for(int x = 0; x < s.Length; x++)
iArray[x] = Convert.ToInt32(s.Substring(x,1));
How do we write C# methods?
After reading this section, you will be able to write methods and understand the concept of (Parameters, Return Value)
We have a line of code and need to put it inside a method to understand how we can write C# methods.
This line of code uses the Sqrt method of the class Math to get the square root of 9. We need to create a method to write to the console screen the square root when we use it (when we call it, Invoke it). Let's take a look at this method :
static void SqrtToConsole(double x)
To understand this method, we need to explain the concept of parameters.
Parameters and parameters value
Many of the methods you call will need information from you to complete their task. For example, the ToIntArray() method in the article take one parameter as a string :
private int ToIntArray(string s) //Here s is a parameter
So this place where we will put the string into called a parameter. We tell the method, "You have one place (a parameter) where the user can put a value here (a parameter value), and you need this value to finish your task". So when you create the method, you specify the parameters that the method will use, and when you call it, you will specify the parameter's value for the parameters. Parameters are the values you specify for your parameters when you call the function. Every parameter in your method has a data type exactly like variables; you must specify it when you create the method. When you call the method, you must specify the parameter value of the same data type or a type that can be converted to that type. The parameters of any method are not accessible outside the method because it's considered local variables for that method.
Consider the following example :
static void SqrtToConsole(double x) // Here x is a parameter
We just created a method called SqrtToConsole that takes only one parameter. Now we need to call the method ( I mean, we need to use the method).
SqrtToConsole(9) // 9 is called a parameter value
We called the method SqrtToConsole with 9 as a parameter value for the parameter x.
After you understand the concept of Parameters, we can explain the code written in the method SqrtToConsole.
static void SqrtToConsole(double x)
We just created a method called SqrtToConsole with one parameter called x of double data type. We use 2 FCL functions here (WriteLine(), Sqrt()) to complete the task.
The Console.WriteLine() method takes one parameter value to write it to the console. Note that the parameter value of this parameter can be an expression. There are 18 overloaded versions of Console.WriteLine() method, and you can check them in Visual Studio.NET Documentation. Some take a parameter value as a string, int, double, object, or other data type.
The Math.Sqrt() method take also one parameter value to get its job done. Here we create our method, and inside it, we call the Console.WriteLine() with a parameter value as the result of the method called Math.Sqrt(x).
Note: Don't forget that x is the parameter of the SqrtToConsole() method, and we use it in Math.Sqrt(x) method so that we tell the compiler to take the parameter value of the SqrtToConsole() method and give it to the Math.Sqrt()so the result will write to the console application.
Let's look at Math.Sqrt() again, please. This method takes a parameter of double data type and Returns the square root of that parameter, so this is the return value that we are talking about here in C# methods.
Consider the following method:
private int AddIntegers(int x, int y)
return x + y ;
Here the AddIntegers() method takes 2 integer numbers and returns the result as an integer too.
The return value must have a type, so here in our method, the return value is of type int, and we must write the int keyword before the method name to specify the return type. Also, we use the return keyword as the end of our method to exit the method and return the value to the method called the AddIntegers() ( I will explain how we can call a method from another method later ). So when you use the return keyword, you tell the compiler to end the method and return a value of the specified type to the calling code. If your method does not return a value, you must use the void keyword in the same place as you do with the return value type (before the method name).
You must understand something called Method Signature or Method Definition. The group of the method names, parameter list, and return value type specify the method signature or method definition. For example, the method AddIntegers() signature is :
- The return data type (int)
- The method name ( AddIntegers )
- The parameter list ( (int x, int y) )
How do we call a C# method?
As you might know that the Main method is the entry point of any C# program, so it's the first method that the compiler will invoke. So any method we created or used from FCL will be called from the Main method. Consider the following example :
We have 2 methods as following :
private void Parent()
// We don't need any code here
private void Son(int x)
// We don't need any code here
We need to call this method from our Main method. All that we need to do like that
static void Main(string args)
We called the 2 methods simply by typing the method's name with 2 empty parentheses if the method's parameter list is empty or with parameter values inside the parenthesis if the method's parameter list contains parameters.
Note: a user-defined method can call other methods like another user-defined method or FCL method.
In this article, we've looked at the basics of methods. They're a powerful tool for organizing your code and making it easier to reuse in different situations. You can also use methods to make your programs more efficient by avoiding redundant work or repetitive tasks. We hope this article has helped clarify any confusion about how methods work in C#!