In this article, I am going to discuss Functions in C# with Examples. Please read our previous article, where we discussed Goto Statement in C# with Examples. As part of this article, you will understand what methods are and their type and how to create and call functions in C# with Examples.
A function is a group of related instructions that performs a specific task. It can be a small or big task, but the function will perform that task completely. Functions take some input as parameters and return the result as a return value. If we write a function, then we can reuse the function multiple times in the program. That means functions allow us to reuse the code without retyping the code.
Let us understand why we need functions with an example. Functions are also called modules or procedures. Instead of writing a single main program, i.e., everything inside the main function, we can break the main function into small manageable size pieces and separate the repeating tasks or smaller tasks as a function.
For Example, if we write one program and put everything inside the main function, then such a type of programming approach is called Monolithic Programming. If your main function contains thousands of lines of code, then it is becoming very difficult to manage. This is actually not a good programming approach.
So, these are the few problems due to monolithic programming. Monolithic means everything is a single unit.
We prefer to break the program into pieces, manageable and small pieces, and reusable pieces. The benefit of this is we can develop piece-wise so we can concentrate on one piece of code at a time. The second thing is that pieces can be distributed among the team of programmers, and they can develop some pieces, and we can collect them together and make it a single program.
So, suppose we break the program into smaller tasks, i.e., into many smaller functions, and each function performs a specific task. In that case, such type of programming is called “modular programming” or “procedural programming,” and this approach is good for development.
As shown in the above image, the first function, i.e., function1(), will perform some specific task, and another function, i.e., function2(), will perform some other task, and similarly, function3() may perform some task. So, in this way, we can break the larger task into smaller simple tasks, and then we can use them all together inside the main function.
Here, in the Modular Programming Approach, you can break the program into smaller tasks, focus on smaller tasks, finish them, and make them perfect. It is easy for one single individual to develop the application, even if you can break this software project into a team of programmers where each programmer will focus on one or many smaller tasks.
This Modular style of programming approach has increased productivity and also reusability. For example, if you want the logic of function2 three times inside the main method, then you need to call function2 three times. That means we are reusing the logic defined in function 2. This is called reusability.
Basically, there are two types of Functions in C#. They are as follows:
Note: The function which is already defined in the framework and available to be used by the developer or programmer is called a built-in function, whereas if the function is defined by the developer or programmer explicitly, then it is called a user-defined function.
In the below example, we are using the built-in WriteLIne function to print the output on the console window and the built-in Sqrt function to get the square root of a given number.
Output: Square Root of 25 is 5
All the predefined functions in C# are contained limited tasks only, i.e., for what purpose the function is designed for the same purpose it should be used. So, whenever a predefined function does not support our requirements, we need to go for user-defined functions.
The User-defined functions in C# are the functions that are created by the programmer so that he/she can use them many times. It reduces the complexity of a big program and optimizes the code. C# allows you to define functions according to your need. The function whose body is implemented by the developer or user is called a user-defined function.
As per client or project requirements, the functions we are developing are called user-defined functions. Always user-defined functions are client-specific functions or project-specific functions only. As a programmer, we have full control of user-defined functions. As a programmer, it is possible to alter or modify any user-defined function’s behavior if required because the coding part is available.
Let us see how to write a function in C#. First of all, the function should have a name that is mandatory. Then it should have a parameter list (the parameters it is taking) which is optional; then the function should have a return type which is mandatory. A function can have an access specifier, which is optional, and a modifier which is also optional. For a better understanding, please have a look at the below image.
Here,
Note: Access Specifiers and Modifiers are not the same. Method and Function are both the same, so we can use the term Method and Function interchangeability.
In the above example,
public is the access specifier
int is the return type
max is the Method Name
(int x, int y) is the Parameters list
And this method does not have any modifiers.
In C# programming language, a Method Signature is consisting of two things, i.e., the Method Name and the Parameter List. The return type is not considered to be a part of the method signature. Later we will discuss why the return type is not considered part of the method signature.
The return statement terminates the execution of a function immediately and returns the control to the calling function. Execution resumes in the calling function at the point immediately following the call. A return statement can also return a value to the calling function. A return statement causes your function to exit and return a value to its caller. In general, the function takes inputs and returns some value. The return statement is used when a function is ready to return a value to its caller.
When a method is invoked (called), a request is made to perform some action, such as setting a value, printing statements, performing some complex calculation, doing some database operation, returning some data, etc. The code we need to invoke a method contains the name of the method to be executed and any data the receiving method requires. The required data for a method is specified in the method’s parameter list.
When we invoke a method, the control gets transferred to the called method. Then the called method returns the control to the caller method (from where we call the method) in the following three conditions.
Let us see how to create and call a method in C#. In the below example, we have implemented the logic to add two numbers and then print the result on the console window, and we have written the logic inside the main method only.
As you can see in the above code, first, we declare two variables, x and y, and then we initialize these two variables with values 10 and 15, respectively. Then we add these two variables and store the result in another variable, i.e., sum, and finally print the sum value in the console, which is what you can see in the output. Let us see how to write the same Program using Function. For a better understanding, please have a look at the below image.
As you can see in the above image, we created a function called Add, which takes two input parameters, a and b, of type integer. This Add function adds the two integer numbers it received as input parameters, stores the result in variable sum, and returns the result.
Now see the main function. From the main function, we are calling the Add function. While calling the Add function, we pass two parameters, i.e., x and y (actually, we pass the values stored in x and y). These parameters’ values will go into the a and b variables. The Add function then adds these two values and returns the result to the calling function (the function from where the Add method is called), i.e., the Main method. The main function then stores the result from the Add method into the variable sum and prints the result on the output window.
To understand the different parts of a function, please look at the image below.
For a better understanding of the function parameters, please look at the image below.
As you can see in the above image, we are passing two values, x, and y, to the Add function, which takes two parameters (a and b). The parameters (x and y) that we are passing to the Add function are called Actual Parameters. The parameters (a and b) which are taken by the Add method are called Formal Parameters. When we call the Add method, the values of actual parameters are copied to the formal parameters. So, the x value, i.e., 10, is copied to a, and the y value, i.e., 15, is copied to b.
When the program starts, i.e., when the main method starts its execution, three variables (x, y, and sum) are declared inside the stack, that is, inside the activation area of the main function. Then the x and y are assigned with values 10 and 15, respectively. And then, the main method calls the Add method. Once the Add method is called, its own activation area is created inside the stack, and it will have its own variables, i.e., variables a, b, and sum are created inside this activation area. Then the value of x i.e. 10, and the value of y i.e. 15, passed to Add function, are copied to the variables a and b, respectively. Then the Add method adds the two numbers and the result is 25, which is stored in the variable sum, and that result, i.e., 25, is returned from the Add method. That result coming from the Add method is stored in the variable sum, and that will be printed in the console window. For a better understanding, please have a look at the following image.
So, this is what happens inside the main memory when we are writing functions. One more point you need to remember is that one function cannot access the variables of other functions. I hope you understand the basics of Functions in the C# language.
In the next article, I am going to discuss Types of User-Defined Functions in C# Language with Examples. In this article, I try to explain Functions in C# Language with Examples. I hope you enjoy the Functions in C# Language with Examples article. I would like to have your feedback. Please post your feedback, question, or comments about this article.