Functions in C#

Functions in C# with Examples

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 are Methods and its type and how to create and call functions in C# with Examples.

What are the Functions of C# Language?

A function is a group of related instructions that performs a specific task. It can be a small task or a big task but the function will perform that task completely. Functions take some input as parameters and return the result as a return value.

Functions are useful for procedural programming or modular programming. If we write a function then we can reuse the function multiple times in the program.

In the C#, a function is a section of the program that contains a set of instructions or code. A method is a set of statements that is referred to by name and can be called (invoked) at any point in a program simply by utilizing the method’s name. Think of a method as a subprogram that acts on data and often returns a value. Each method has its own name.

A function is a collection of statements that perform a specific task and return the result to the caller. A function can perform a specific task without returning anything. Functions allow us to reuse the code without retyping the code. They are basically referred to as time savers, which means that they allow you to have the repetition of sections of code without having to retype the code.

Why do we need functions?

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. writing everything inside the main function, we can break the main function into small manageable size pieces and we can separate the repeating tasks or smaller tasks as a function.

For example; if we write one program, and if we put everything inside the main function, then such 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.

Why do we need functions?

Problems in Monolithic Programming:
  1. First problem: if there is an error in a single line then it’s an error in the entire program or entire main function.
  2. Second problem: 10000 lines of code, we cannot finish it in one hour or one day, it might take a few days and throughout the time we should remember everything. Then only we can make changes or write new lines in the program. So, we should memorize the whole program.
  3. Third problem: How many people can write this one single main function? Only one person can write. We cannot make it as teamwork and more than one people can’t work on the same main function. So, work cannot be distributed in a team.
  4. Fourth problem: when this program becomes very big, it may fit in some computer memories and it may not fit in some of the memories. It Depends on the size and depends on the hardware contribution of the computer on which you are running.

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 re-usable 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 pieces can be distributed among the team of programmers and they can develop some set of pieces and we can collect them together and make it as a single program.

So, if we broke the program into smaller tasks, i.e. into many smaller functions and each function performs a specific task, then such type of programming is called “modular programming” or “procedural programming” and this approach is good for development.

Functions in C# with Examples

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 and you can focus on smaller tasks and 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 simply need to call function2 three times. That means we are reusing the logic defined in function 2. This is called reusability.

Types of Functions in C#:

Basically, there are two types of Functions in C#. They are as follows:

  1. Built-in Functions
  2. User-Defined Functions

Types of Functions in C#

User-Defined Functions in C#:

The user-defined functions are created by the programmer. A function must be declared within a specific class. It is defined with the name of the method, followed by parentheses “()”.

How to write a function in C#?

Let us see how to write a function in C#. First of all, the function should have a name. Then it should have a parameter list or also called argument list (the parameters it is taking), then the function should have a return type. For a better understanding, please have a look at the below image.

How to Create a User-Defined Method in C#

Here,

  1. Modifier: It defines the type of access to the method. It is optional to use.
  2. Return type: It defines the return type of value of the method. A function may or may not return a value but it can return at most one value. It cannot return multiple values but it can take multiple values as parameters. If the function is not returning any value, then the return type should be void.
  3. MethodName: It defines the name of the method. The method signature consists of the method name and parameter list. The Methods are identified by their name. The rules for giving function names are the same as the rules for giving the variable names. Same rules you should follow for giving function names also.
  4. Parameter List: It defines the list of parameters. It is the type, order, and the number of parameters of the methods. A function can take 0 or more parameters means it may not take any input.
  5. Method Body: The body of the method defines the code or list of statements you need to be executed. It is enclosed within braces.

Note: Function does not have access to use the variables of other functions (even the main function). So, if you want the function to use some variable of another function then you have passed that variable as an argument to the function.

Example to Create User-Defined Function in C#:

Example to Create User-Defined Function in C#

In the above example,
public: modifier
int: return type
max: Method Name
(int x, int y): Parameters list

What is Function Signature in C#?

In C# programming language, a method signature is the method name and the number, type, and order of its parameters. The return type is not considered to be a part of the method signature.

  1. Function Name: A method name is typically a single word that should be a verb in lowercase or multi-word, that begins with a verb in lowercase followed by an adjective, noun. After the first word, the first letter of each word should be capitalized. For example, calculateSum.
  2. Function Parameter: These are values passed to a method. We can pass any number of arguments to a method but just separate them with a comma. Parameters are specified after the method name in a class, inside parentheses. Data can be passed to functions as a parameter. Actually, parameters act as variables inside the method.
Example to Understand Function Signature in C#:

Example to Understand Function Signature in C#

How to call a method in C#?

When a method is invoked (called), a request is made to perform some action, such as setting a value, printing statements, returning an answer, etc. The code to invoke the method contains the name of the method to be executed and any needed data that the receiving method requires. The required data for a method is specified in the method’s parameter list.

When a program invokes a method, the program control gets transferred to the called method. This called method then returns control to the caller in three conditions, when −

  1. The return statement is executed.
  2. It reaches the method ending closing brace.
  3. It throws an exception.
Example to Understand Functions in C# Language:

In the below example, we have implemented the logic to add two numbers inside the main function only.

using System;
namespace FunctionDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int x, y;
            x = 10;
            y = 15;
            int sum = x + y;
            Console.WriteLine($"Sum is {sum}");
            Console.ReadKey();
        }
    }
}

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 value of the sum in the console and that 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.

Example to Understand Functions in C# Language

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 and stores the result in variable sum and returns that result.

Now see the main function. From the main function, we are calling the Add function and while calling the Add function we are passing two parameters i.e. x and y (actually we are passing the values stored in x and y) and these parameters’ values will go into a and b variables. The Add function then adds these two values and returns the result to the calling function (the function is called the add method) i.e. the main method. The main function then stores the result coming from the Add method into the variable sum and then prints the result on the output window.

Complete Example Code is Given Below:
using System;
namespace FunctionDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int x, y;
            x = 10;
            y = 15;
            int sum = Add(x, y);
            Console.WriteLine($"Sum is {sum}");
            Console.ReadKey();
        }

        static int Add(int a, int b)
        {
            int sum = a + b;
            return sum;
        }
    }
}
Different Parts of a Function in C#:

To understand the different parts of a function, please have a look at the below image.

Different Parts of a Function in C#

What are the Parameters of a function?

For a better understanding of the function parameters, please have a look at the below image.

What are the Parameters of a function?

As you can see in the above image, we are passing two values x and y to the Add function which is taking 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, x value i.e. 10 is copied to a, and y value i.e. 15 is copied to b.

How does it work inside the Main memory?

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 variable 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 better understanding, please have a look at the following image.

How does it work inside the Main memory?

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.

Advantages of functions in C# Language or Why do we need functions in C# Language?
  1. Reusability: By using functions we can create re-usability blocks i.e. develop once and use multiple times.
  2. Code Maintenance: When we are developing the application by using functions, then it is easy to maintain code for future enhancement.
  3. Code Sharing: A function may be used by many other programs.
  4. Flexible Debugging: It is easy to locate and isolate a faulty function for further investigations.
  5. Data Protection: Functions can be used to protect data and local data. Local data is available only within a function when the function is being executed.
  6. Code Reduced: Reduces the size of the code, duplicate statements are replaced by function calls.
Advantages of Using Standard Library functions in C# Language:
  1. One of the most important reasons you should use library functions is simply because they work. These functions have gone through multiple testing phases and are easy to use.
  2. The functions are optimized for performance. Since, the functions are “standard library” functions, a dedicated group of developers constantly makes them better. In the process, they are able to create the most efficient code optimized for maximum performance.
  3. It saves considerable development time. Since the general functions like printing to a screen, calculating the square root, and many more are already written. You shouldn’t worry about creating them once again.
Example to understand Built-in C# Functions:

In the below example, we are using the built-in Sqrt function to get the square root of a given number.

using System;
namespace FunctionDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int number = 25;
            double squareRoot = Math.Sqrt(number);
            Console.WriteLine($"Square Root of {number} is {squareRoot}");
            Console.ReadKey();
        }
    }
}

Output: Square Root of 25 is 5

What are the limitations of Pre-Defined Functions in C# Language?

All the predefined functions in C# are contained limited tasks only i.e. for what purpose function is designed for the same purpose it should be used. So, whenever a predefined function is not supporting our requirements then we need to go for user-defined functions.

User-Defined Functions in C# Language:

The User-defined functions in C# are the functions that are created by the programmer so that he/she can use it 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 are having full control of user-defined functions. As a programmer, it is possible to alter or modify the behavior of any user-defined functions if it is required because the coding part is available.

Advantages of User-Defined Functions in C#:
  1. The program will be easier to understand, maintain, and debug.
  2. Reusable codes that can be used in other programs
  3. A large program can be divided into smaller modules. Hence, a large project can be divided among many programmers.

Frequently Asked Functions Interview Questions

Will the functions occupy space in memory?

Yes, the machine code of a function is kept code section.

Will a function occupy space even if it is not called?

Yes, if a function is defined in a program or included in the library, it will occupy space in the code section.

Where the memory for the variable of a function is created?

Memory for the variables used in a function is created in the stack.

When the memory for variables will be allocated?

Memory for the variables will be allocated at runtime when the function is called and deleted when the function ends.

Is the memory for variables allocated freshly for each call?

For “for each” call of a function memory for the variables is created freshly in the stack.

What is the return type of a function?

When a function is called by passing parameters, it will compute and get the results. A function can return the result to a calling function. The return type is the data type of a value returned by the function.

What is void?

If a function is not returning any value, then its return type is mentioned as void.

Difference between int main() and void main()
  1. void main() means the main function is not returning any value.
  2. int main() means main function will return 0; 0 is a success code.
  3. The function has terminated successfully. The main() will return the value to the operating system, like windows.

In the next article, I am going to discuss Types of User-Defined Functions in C# Language with Examples. Here, 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.

Leave a Reply

Your email address will not be published.