Functions C#
Functions C#
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.
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., 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.
1/2
00:1
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.
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
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.
Advantages of Using Standard Library functions in C# Language:
1. One of the most important reasons you should use library functions or built-in
functions is simply because they work. These built-in functions or pre-defined
functions have already gone through multiple testing phases and are easy to use.
2. The built-in functions are optimized for performance. So, you will get better
performance with built-in functions. Since the functions are “standard library”
functions, a dedicated group of developers is constantly working on them to make
them better.
3. It saves development time. 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. You need to use them and save your time.
Example to understand Built-in C# Functions:
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.
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 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.
What are 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 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.
Advantages of User-Defined Functions in C#:
1. The application code will be easier to understand, maintain, and debug.
2. We can write the code once, and we can reuse the code in many places, i.e., code
reusability.
3. Program size reduced. As the duplicate code is put inside a single function, the size
of the application code is going to be reduced.
How to Create a User-Defined Function in C#?
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,
1. Function Name: It is mandatory, and it defines the name of the method or function.
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 variable names. Same rules you should follow for giving function
names also.
2. Parameter List: It is Optional and defines the list of parameters. A function that can
take 0 or more parameters may not take any input.
3. Return Type: It is Mandatory and defines the method’s return type value. A function
may or may not return a value, but it can return at most one value. It cannot return
multiple values but can take multiple values as parameters. If the function is not
returning any value, then the return type should be void.
4. Access Specifier: It is Optional and defines the method’s scope. That means it
defines the accessibility of the method, such as private, protected, public, etc.
5. Modifier: It is optional and defines the method’s access type. For example, static,
virtual, partial, sealed, etc. If you declare the method with a static modifier, then you
can access the method directly without creating an instance. If you declare the
method with the sealed modifier, then this method is not going to be overridden
under a child class. And if you declare the method with the partial modifier, then you
can split the method definition into two parts.
6. Function Body: The function’s body defines the code or list of statements you need
to execute the function call. It is enclosed within curly braces.
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.
Example to Create User-Defined Function in C#:
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.
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 look at the image below.
What are the Parameters of a function?
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.
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 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.
There are four types of user-defined functions in C#. They are as follows:
1. Functions with No Argument and No Return Type.
2. Functions with Argument and No Return Type.
3. Functions with No Argument and with Return Type.
4. Functions with Argument and with Return Type
Let us understand each of these function types with examples.
No Arguments Passed and No Return Value Function in C#:
When a function has no arguments, it does not receive any data from the calling function.
Similarly, when it does not return a value, the calling function does not receive any data
from the called function. So, there is no data transfer between the calling and called
functions. A function that does not return any value cannot be used in an expression. It can
only be used as an independent statement.
Example to Understand No Arguments Passed and No Return Value
Function in C# Language:
In the below example, the Sum() function does not take any parameters, or even it does not
return a value. The return type of the function is void. Hence, no value is returned from the
function.
using System;
namespace FunctionDemo
{
class Program
{
static void Main(string[] args)
{
Sum();
Console.ReadKey();
}
static void Sum()
{
int x = 10;
int y = 20;
int sum = x + y;
Console.WriteLine($"Sum of {x} and {y} is {sum}");
}
}
}
Output: Sum of 10 and 20 is 30
No Arguments Passed but Return a Value Function in C#:
When a function has no arguments, it receives no data from the calling function but returns
a value. The calling function receives the data from the called function. So, there is no data
transfer between the calling function to called function but data transfer from the called
function to the calling function. The called function is executed line by line in a normal
fashion until the return statement is encountered.
Example to Understand No Arguments Passed but Return a Value
Function in C# Language:
In the below example, the empty parentheses in int Result = Sum(); statement indicates
that no argument is passed to the function. And the value returned from the function is
assigned to the Result variable. Here, the Sum() function will add the two numbers and
returns the result.
using System;
namespace FunctionDemo
{
class Program
{
static void Main(string[] args)
{
int Result=Sum();
Console.WriteLine($"Sum is {Result}");
Console.ReadKey();
}
static int Sum()
{
int x = 10;
int y = 20;
int sum = x + y;
return sum;
}
}
}
Output: Sum is 30
Argument Passed but no Return Value Function in C# Language:
When a function has arguments, it receives data from the calling function but does not
return any value. So, there is data transfer between the calling function to called function,
but there is no data transfer from the called function to the calling function. The nature of
data communication between the calling function and the called function with arguments but
no return value.
Example to Understand Argument Passed but no Return Value Function
in C# Language:
In the example below, we pass two values to the Sum function, but the Sum function does
not return any value to the main function.
using System;
namespace FunctionDemo
{
class Program
{
static void Main(string[] args)
{
int x = 10, y = 20;
Sum(x, y);
Console.ReadKey();
}
static void Sum(int x, int y)
{
int sum = x + y;
Console.WriteLine($"Sum is {sum}");
}
}
}
Output: Sum is 30
Argument Passed and Return Value Function in C# Language:
A self-contained and independent function should behave like a “black box” that receives an
input and outputs a value. Such functions will have two-way data communication.
Example to Understand Argument Passed and Return Value Function in
C# Language:
using System;
namespace FunctionDemo
{
class Program
{
static void Main(string[] args)
{
int x = 10, y = 20;
int Result = Sum(x, y);
Console.WriteLine($"Sum is {Result}");
Console.ReadKey();
}
static int Sum(int x, int y)
{
int sum = x + y;
return sum;
}
}
}
Output: Sum is 30
What is Function Overloading in C#?
In C#, we can write more than one function with the same name, but with a different
argument or parameter list, and when we do so, it is called function overloading. Let us
understand this with an example.
Here we have created another function with the same name, ‘add’, but it takes 3
parameters. Inside the main function, we have called ‘add(x,y,z)’ and stored the result in
the ‘d’ variable. So, we can have two functions with the same name but with different
parameters.
So when we call “add(a, b)” it will be calling add(int x, int y), and when we call ‘add(a, b, c)’
it will be “add(int x, int y, int z)”. The C# compiler can differentiate between these two
functions, and this is the concept of function overloading in C#.
Example to Understand Function Overloading in C#:
using System;
namespace FunctionDemo
{
class Program
{
static void Main(string[] args)
{
int a = 10, b = 2, c, d;
c = add(a, b);
Console.WriteLine($"Sum of {a} and {b} is {c}");
d = add(a, b, c);
Console.WriteLine($"Sum of {a} and {b} and {c} is {d}");
Console.ReadKey();
}
static int add(int x, int y)
{
return x + y;
}
static int add(int x, int y, int z)
{
return x + y + z;
}
}
}
Output:
Above are the signatures of the different ‘add’ functions. Now let us check which is valid or
which is invalid.
1. int add(int, int) is valid; it takes 2 ‘int’ type parameters and returns the ‘int’ value.
2. float add(float, float) is valid as it takes 2 ‘float’ parameters and returns the ‘float’
value. It takes the same number of parameters but different data types as compared
to the first one.
3. int add(int, int, int) is valid as it takes 3 ‘int’ parameters and returns the ‘int’ value. It
takes a different number of parameters but has the same data types as compared to
the first one.
4. float add(int, int) is invalid; it is the same as the first function, which takes the
same number of parameters and the same type of parameters. So, this is invalid. It
doesn’t matter what type of data a function is returning. If two functions have the
same number of parameters and of the same type, then this is invalid.
Example to understand function overloading in C#
using System;
namespace FunctionDemo
{
class Program
{
static void Main(string[] args)
{
int a = 10, b = 2, c, d;
c = add(a, b);
Console.WriteLine($"Sum of {a} and {b} is {c}");
d = add(a, b, c);
Console.WriteLine($"Sum of {a} and {b} and {c} is {d}");
Console.WriteLine($"Sum of 10.5 and 25.6 is {add(10.5f, 25.6f)}");
Console.ReadKey();
}
static int add(int x, int y)
{
return x + y;
}
static int add(int x, int y, int z)
{
return x + y + z;
}
static float add(float x, float y)
{
return x + y;
}
}
}
Output:
In the next article, I am going to discuss Call by Value and Call by Reference in C# with
Examples. Here, in this article, I try to explain the Types of User-Defined Functions in
C# Language with Examples. I hope you enjoy this Types of User-Defined Functions in C#
with examples article. I would like to have your feedback. Please post your feedback,
question, or comments about this article.