In C#, a function represents a collection of code lines or a sequence of directives designed to accomplish a particular operation. Its execution occurs upon invoking the function, and it is alternatively referred to as a method. The method is enclosed within a class, serving to enhance the comprehensibility, versatility, and sustainability of the codebase.
Syntax
It has the following syntax.
Class program
{
<access_specifier> <return_type> Method_Name()
{
// block of code
}
}
Where,
- access_specifier: It defines the accessibility of the method.
- Return_type: It specifies the return type value that the function returns.
- Method_Name: It defines the name of the function.
C# Example of Functions
Let's consider an example to demonstrate the functionalities in C#.
Example
using System;
class Program
{
static void welcome() // create the function
{
Console.WriteLine("Hello, welcome to C# Tutorial.");
}
static void Main()
{
welcome(); // call the function
}
}
Output:
Hello, welcome to C# Tutorial.
Explanation:
In this instance, we define the static method called greeting. Subsequently, we employ the Console.WriteLine method to display the result and proceed to invoke the method within the main function.
Definition, Declaration, and Initialization of Function
Here, we will explore the process of defining, declaring, and initializing a function in C#.
1) Function Declaration
In C# , a function declaration is the first step to creating the function. A function should be declared before calling it.
Syntax:
Return_Type FunctionName(Parameters);
Example:
Let's consider a straightforward example to define a function in C#.
int sum(int a, int b);
2) Function Definition:
In C#, the function declaration is employed to specify the purpose or functionality of a function.
Syntax:
It has the following syntax.
ReturnType FunctionName(Parameters)
{
// statements
}
Function Definition Example:
Let's consider a straightforward example to demonstrate the declaration of a function in C#.
int sum(int a, int b)
{
int s;
s = a+b;
return s;
}
Function Initialization
In C#, this involves declaring a function and subsequently invoking it with concrete values.
Syntax:
It has the following syntax:
FunctionName(arguments);
Example:
Let's consider a basic example to explain the concept of function initialization in C#.
Sum(20.30);
Simple Function Example in C#
Let's consider a straightforward example to demonstrate functions in C#.
Example
using System;
class Program
{
// Simple function that adds two numbers
static void AddNumbers(int x, int y)
{
int sum = x + y;
Console.WriteLine("Sum: " + sum);
}
static void Main()
{
// Calling the function
AddNumbers(15, 25);
}
}
Output:
Sum: 40
Explanation:
In this instance, we are examining the AddNumbers function with a pair of input parameters. Subsequently, it computes the total and presents the result utilizing the Console.WriteLine method. Ultimately, the function is invoked from the main function with two values, 15 and 20, as arguments.
Needs of Functions
In C# language, there are several cases where functions are required. Some of them are as follows:
- It is utilized to reduce the length of the source code.
- It is utilized to find errors easily.
- It is utilized to call the block of code one or many times.
- It is utilized to make the program more understandable.
Types of Function
The function can be invoked multiple times, offering modularity and code reusability. In C#, there are primarily two categories of functions:
- Built-in Function
- Custom Function
Here, we will discuss these functions one by one.
Pre-defined Function
In the C# programming language, predefined functions refer to the built-in functions that have already been developed by the compiler. These functions are commonly referred to as library functions. A variety of pre-defined functions are available, including Console.WriteLine, Console.ReadLine, Console.Clear, Math.Abs, Math.Sqrt, Math.Pow, Math.Round, and more.
Syntax
It has the following syntax.
ClassName.MethodName(arguments);
Where,
- ClaasName: It represents the classname that stores the methods. The examples of ClassName are Console, Math, and String.
- MethodName: It has stored the predefined function. Examples of predefined functions are Sqrt, WriteLine, and ToUpper.
- Arguments: The arguments are used to pass the value to the methods.
C# Example of Predefined Function
Let's consider an instance to demonstrate the built-in function in C#.
Example
using System;
class Program
{
static void Main()
{
double number = 25; // Assign the value
double sq = Math.Sqrt(number); // Predefined function
Console.WriteLine("The square root of " + number + " is " + sq);
}
}
Output:
The square root of 25 is 5
Explanation:
In this instance, we are utilizing a built-in function to determine the square root of numerical values. Initially, a variable of type double is declared and initialized with a specific value. Subsequently, the Math.Sqrt function is employed to compute the square root of the assigned number. Lastly, the Console.WriteLine method is used to display the resulting output.
User-defined function
In the C# programming language, a custom function is one that the developer creates to carry out a particular task. There is no requirement for any predefined library or function to execute the desired operation. These functions are valuable for enhancing the reusability, readability, and maintainability of the codebase.
C# Example of User-defined Function
Let's consider a scenario to demonstrate the user-defined method in C#.
Example
using System;
class Program
{
static void Addition() // user define function
{
int m = 10;
int n = 20;
int sum = m + n;
Console.WriteLine(" The Sum of the number is " + sum);
}
static void Main()
{
Addition(); // call the function
}
}
Output:
The Sum of the numbers is 30
Explanation:
In this illustration, we showcase the process of summing two numbers through a custom function. Initially, create a function called Add, specifying two variables of integer data type. Subsequently, perform the addition operation on the two numbers and exhibit the result using the Console.WriteLine method. Lastly, invoke the function within the main method to run the operation.
Types of User-defined Function
In C#, there are four types of user-defined functions
- Function with no Arguments and no return type
- Function with Arguments and no return type.
- Function with no Arguments and with a return type.
- Functions with Arguments and with Return Type.
Here, we will explore various custom functions in C# individually.
Function with no Arguments and no return type
In C#, a user-defined function without any parameters and no return type signifies a function that doesn't accept inputs and doesn't return any value to the caller. This type of function is declared using the void return type.
Syntax
It has the following syntax.
void FunctionName() // function with no arguments and no return type
{
// no return value
Return;
}
A function in C# without any parameters and return type is an example of a void function. This type of function does not accept any inputs and does not return any value after execution. It is mainly used for performing actions or tasks without needing to pass or receive data.
Let's consider a basic example to demonstrate C# functions that do not require any arguments and do not return any value.
Example
using System;
class Program
{
// Void function with no arguments
static void Intro()
{
Console.WriteLine("Hello! Welcome to C# Programming tech");
}
static void Main()
{
Intro(); // Call the function
}
}
Output:
Hello! Welcome to C# Programming tech
Explanation:
In this instance, a function named Intro is crafted without any parameters or return type. Subsequently, the Console.WriteLine method is employed to exhibit the result. Following this, the function is invoked within the main method for execution.
Function with Arguments and no return type
In C#, a user-defined function without a return type but with arguments is a function that receives parameters but does not send back any result to the calling function.
Syntax:
It has the following syntax.
void FunctionName (type1 argument1, type2 argument2)
{
// program
return;
}
A function in C# that takes arguments but does not have a return type is exemplified below:
void PrintMessage(string message)
{
Console.WriteLine(message);
}
In the given example, the function named PrintMessage accepts a parameter message of type string and then prints out the message to the console using Console.WriteLine.
Let's consider a basic example to demonstrate C# functions with parameters and void return type.
Example
using System;
class Program
{
static void Sum(int m, int n) // create function as arguments but no return type
{
int s = m * n; // multiply two numbers
Console.WriteLine("The Multiplication is: " +s);
}
static void Main(string[] args)
{
Sum(5, 10); // calling function
}
}
Output:
The sum is: 50
Explanation:
In this illustration, we are showcasing a sum function that accepts two integer parameters, performs multiplication on them, and showcases the outcome. Subsequently, the function is invoked from the main function with the input values of 5 and 10. Ultimately, the result is exhibited utilizing the Console.WriteLine method.
Function with no Arguments and with Return Type
In C#, a user-defined function without any parameters but with a return type provides a value back to the calling code.
Syntax:
It has the following syntax.
return_type FunctionName()
{
// block of code
return value;
}
A function without any parameters and with a return type is demonstrated below:
#include <iostream>
using namespace std;
// Function declaration
int addNumbers();
int main() {
int result;
// Function call
result = addNumbers();
cout << "The sum is: " << result;
return 0;
}
// Function definition
int addNumbers() {
int a = 5, b = 10;
int sum = a + b;
return sum;
}
Let's consider a basic example to demonstrate C# functions that do not take any arguments but have a return type.
Example
using System;
class Program
{
// no arguments with string returns type function
static string GetWelcomeMessage()
{
return "Welcome to C# Programming tech!";
}
static void Main(string[] args)
{
// Call the method and store the returned string
string message = GetWelcomeMessage();
Console.WriteLine(message);
}
}
Output:
Welcome to C# Programming tech!
Explanation:
In this instance, we've defined a function called GetWelcomeMessage, which doesn't take any arguments and returns a string value. Following this, invoke the function within the main function to capture the string value. Lastly, utilize Console.WriteLine to showcase the result.
Functions with Arguments and with Return Type
In C#, a user-created function with parameters and a specified return type processes input values and sends back a result to the calling function.
Syntax:
It has the following syntax.
return_type FunctionName(type1 argument1, type2 arguments2, … typeN argumentN)
{
// block of code
return value;
}
Functions with Parameters and Return Type Example
Let's consider a basic scenario to demonstrate C# functions that do not take any arguments but return a string data type.
Example
using System;
class Program
{
// create a function with an argument and with a return type
static int Multiply(int x, int y)
{
return x * y;
}
static void Main(string[] args)
{
// Call the method with arguments and store the result
int result = Multiply(3, 5);
Console.WriteLine("The product is: " + result);
}
}
Output:
The product is 15
Explanation:
In this instance, a function named Multiply has been crafted with parameters to compute and return an integer value represented as a string. Subsequently, invoke this function within the main block to capture the string result. Conclusively, employ Console.WriteLine to exhibit the final outcome.
Function Parameter in C#
There are three types of function parameters in C#. These are as follows.
- Pass-by value
- Pass-by reference
- Pass-by Pointer
Pass by Value
In C#, pass-by-value is employed to transfer a duplicate of the initial value of the function instead of a reference.
Pass by Value Example in C#
Let's consider a basic example to demonstrate the pass by value function parameter in C#.
Example
using System;
class Program
{
static void Main()
{
int number = 5; // Declare and initialize a variable
Console.WriteLine("Before function call: " + number);
ChangeValue(number); // Pass the variable to the function (by value)
Console.WriteLine("After function call: " + number);
}
static void ChangeValue(int num)
{
num = 10; // Change the value of the parameter inside the method
Console.WriteLine("Inside method: " + num);
}
}
Output:
Before function call: 5
Inside method: 10
After function call: 5
Explanation:
In this example, we demonstrate the pass-by-value parameter. We have taken the ChangeValue method that receives a copy of the variable number that changes its value to 10, and display the output using the Console.WriteLine function. However, the actual number in the main function does not change because changes to the parameter inside the method don't affect the original value.
Pass by Reference
In C#, the pass by reference method involves receiving the precise memory location of the arguments rather than a duplicate. This allows any modifications made within the function to have a direct impact on the original value.
Pass by Reference Example in C#
Let's consider a basic example to demonstrate the Pass-by-reference function parameter in C#.
Example
using System;
class Program
{
static void Main()
{
int number = 5;
Console.WriteLine("Before: " + number);
Change(ref number); // Pass by reference
Console.WriteLine("After: " + number);
}
static void Change(ref int x)
{
x = 10; // Changes the original variable
}
}
Output:
Before: 5
After: 10
Explanation:
In this instance, we showcase pass-by-reference in C# by utilizing the ref keyword. Subsequently, the variable named number is passed to the Change method by reference, enabling the method to alter the original variable's value.
Pass by Pointer
In C#, we provide the reference or location of the variable in a pointer. The function then changes the data stored at the specified address.
Syntax:
It has the following syntax.
using System;
class ClassName
{
static unsafe void Main()
{
DataType variableName = value;
Console.WriteLine("Before: " + variableName);
FunctionName(&variableName);
Console.WriteLine("After: " + variableName);
}
static unsafe void FunctionName(DataType* pointerName)
{
*pointerName = newValue;
}
}
Advantages of functions in C#
Several advantages of functions in C# are as follows:
- Code Reusability: The main advantage of a function is code reusability. It means that create the function in C#, we can call it many times. Therefore, we don't need to write the same code again and again.
- Code Optimization: The function is used to make the code optimized. Suppose we have to check 10 numbers, whether it is even or not. Without using the function, we need to write the even number logic 10 times. Therefore, there is a repetition of code. However, if we use a function, we need to write the logic at once, and we can reuse it several times.
- Improved Readability and Maintainability: The programs are more efficient and readable it is easy for the programmer to maintain the code.
- Debugging and Testing Made Easier: The function assists debugging and testing because the program error becomes confined to a single function.
Conclusion
In summary, the C# method plays a crucial role for programmers in building software applications. It serves as the primary focus during development, comprising a series of commands designed to execute particular tasks. These methods aid in optimizing code efficiency and simplifying code maintenance.
C# Function FAQs
1) What is the function in C#?
In C#, a function is a segment of code containing a series of instructions designed to accomplish a particular objective. It is executed upon invocation.
2) Why should the function be used in C#?
In C#, the method plays a crucial role for developers in building software applications. It plays a significant role in shortening the source code and enhancing program comprehension. Additionally, it enhances code reusability, readability, and maintainability.
3) What is the syntax of a function in C#?
It has the following syntax.
class class_name
{
<access_specifier> <return_type> Method_Name()
{
// block of code
}
}
4) What are the differences between void and non-void functions in C#?
In C#, a void method does not provide a return value, whereas a non-void method yields a specific value upon completion.
5) What are the types of functions in C#?
There exist primarily two categories of functions within C#:
- Built-in functions
- Custom functions