Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is Functions in C#?
3.
Syntax of Function in C# 
4.
Example of Function in C#
5.
Local Functions in C#
6.
Advantages of Functions in C#
7.
Disadvantages of Functions in C#
8.
Passing Parameters to a Function in C#
8.1.
Passing Parameters by Value
8.2.
Passing Parameters by Reference
8.3.
Passing Parameters by Output
9.
Frequently Asked Questions
9.1.
What are non-parameterized functions in C#?
9.2.
Where can local functions be created?
9.3.
Mention a difference between the output parameters and the reference parameters.
9.4.
When are output parameters beneficial?
9.5.
What is the "Main" function in C#?
10.
Conclusion
Last Updated: Sep 10, 2024
Easy

Functions in C#

Author Hari Sapna Nair
4 upvotes

Introduction

function is a group of statements to perform a specific task. It could be statements for doing repetitive work or a specific task like printing. A function helps us simplify the code by breaking it into smaller parts. It also saves us from writing the same code again. We can write a function once and call it whenever required without writing the same set of statements again and again.

Functions in C#

Now we will learn about functions in C#, local functions in C#, and the different ways to pass parameters to the function in detail.

Recommended Topic, Palindrome in C# and Ienumerable vs Iqueryable.

What is Functions in C#?

A function in C# allows us to encapsulate a code block and call it from other parts of the code. It executes statements specified in the code block. 

A function in C# consists of the following parts:

  • Function name: The unique name used to make a function call.
  • Return type: It specifies the data type of function's return value.
  • Body: The block that contains the executable statements.
  • Access specifier: Specifies the function's accessibility in the different parts of the code.
  • Parameters: The list of arguments passed to the function during the call.

Syntax of Function in C# 

<access specifier><return type>functionName(<parameters>)  { 
   // function body 
}

Here, the access specifier, parameters, and the return statement are optional.

Example of Function in C#

Let us help you understand how to define and call functions in C# with an example.

using System;

public class Program {
 // User defined function
 public void display(string name) { 
   Console.WriteLine("I am " + name); 
 } 
 
  public static void Main(string[] args) { 
   string name = "Sapna";
   // Creating Object
   Program program = new Program();
   // Calling Function  
   program.display(name);          
 } 
}

Output

I am Sapna

Here, we are calling a user-defined parameterized function "display" with the return type as void. 

Local Functions in C#

A local function in C# is a private function of a function whose scope is limited to that function in which it is created. The return type of local function is similar to the return type of function in which it is defined. We can only call the local function from their container members.

A Local function can access the local variables defined inside the container function, including the function parameters.
 Example

Let us help you understand functions in C# with an example.

using System;

public class Program {
 public static void Main(string[] args) { 
   // Local function
   void display(string name) { 
     Console.WriteLine("I am " + name); 
   } 
  
   string name = "Sapna";
   display(name);          
 } 
}

Output

I am Sapna

Advantages of Functions in C#

The advantages of local functions in C# are as follows:-

  • The local function makes our program more readable.
  • It allows us to create local generic functions.
  • We can pass out/ref parameters in the local functions. 
  • It allows us to use params in local functions.

Disadvantages of Functions in C#

The disadvantages of local functions in C# are as follows:-

  • We cannot use any member access modifiers in the local function definition, including the private keyword, as they are by default private.
  • We cannot use the static keyword with the local function.
  • We cannot apply attributes to the local function, its parameters, or its parameter type.
  • Overloading is not allowed for the local functions.

Passing Parameters to a Function in C#

When a function with parameters is called, we must pass the parameters to the function. There are different ways to pass parameters to a function. They are as follows:

Passing Parameters by Value

Passing parameters by value is the default way for passing parameters to a function. A new storage location is created for each value parameter when a function is called in this mechanism. The values of the actual parameters are copied into the new storage location. Hence, the changes made to the parameter inside the method do not affect the argument. 

Example

Let us help you understand passing parameters by value with an example. In this example, we will swap the values between two variables.

using System;

public class Program {
     void swap(int x, int y) {
        int temp = x;
        x = y;   
        y = temp;
     }
  
     static void Main(string[] args) {
        Program program = new Program();
       
        // Local variable definition
        int a = 5;
        int b = 10;
       
        Console.WriteLine("Before Swap");
        Console.WriteLine("Value of a : "+ a);
        Console.WriteLine("Value of b : "+ b);
       
        // Calling the swap function to swap the values
        program.swap(a, b);
       
        Console.WriteLine("After Swap");
        Console.WriteLine("Value of a : "+ a);
        Console.WriteLine("Value of b : "+ b);
     }
}

Output

Before Swap
Value of a : 5
Value of b : 10
After Swap
Value of a : 5
Value of b : 10

There is no change in the values of "a" and "b" even though they had changed inside the function.

Passing Parameters by Reference

A reference parameter is a reference to a memory location of a variable. When we pass parameters by reference, a new storage location is not created for these parameters, unlike value parameters. The reference parameters represent the exact memory location as the actual parameters supplied to the function. To declare the reference parameters, we use the ref keyword. 

Example

Let us help you understand passing parameters by reference with an example. In this example, we will swap the values between two variables.

using System;
public class Program {
    void swap(ref int x, ref int y) {
       int temp = x;
       x = y;  
       y = temp;
    }
     static void Main(string[] args) {
       Program program = new Program();
     
       // Local variable definition
       int a = 5;
       int b = 10;
     
       Console.WriteLine("Before Swap");
       Console.WriteLine("Value of a : "+ a);
       Console.WriteLine("Value of b : "+ b);
     
       // Calling the swap function to swap the values
       program.swap(ref a, ref b);
     
       Console.WriteLine("After Swap");
       Console.WriteLine("Value of a : "+ a);
       Console.WriteLine("Value of b : "+ b);
    }
}

Output

Before Swap
Value of a : 5
Value of b : 10
After Swap
Value of a : 10
Value of b : 5

Values have changed inside the swap function, which reflects in the Main function.

Passing Parameters by Output

Generally, a return statement returns only one value from a function. However, we can return two values from a function using the output parameters. To declare the output parameters, we use the out keyword. 

Example

Let us help you understand passing parameters by output with an example. In this example, we will convert numbers from binary to decimal.

using System;
public class Program {
    void conversion(out int x, out int y) {
       // Binary representation of 4
       x = 100;
       x = Convert.ToInt32(x.ToString(), 2);

       // Binary representation of 5
       y = 101;
       y = Convert.ToInt32(y.ToString(), 2);
    }
     static void Main(string[] args) {
       Program program = new Program();
     
       // Local variable
       int num1, num2;
     
       // Calling the conversion function to convert the values from binary to decimal
       program.conversion(out num1, out num2);
       Console.WriteLine("num1: " + num1);
       Console.WriteLine("num2: " + num2);
    }
}

Output

num1: 4
num2: 5

Note: Here, the variable supplied as the output parameter need not be assigned any value. 

Frequently Asked Questions

What are non-parameterized functions in C#?

A function in C# can have zero or any number of parameters in the argument list. Functions without a parameter are also known as non-parameterized functions in C#.

Where can local functions be created?

Local functions in C# are declared inside functions, property accessors, anonymous methods, constructors, event accessors, finalizers, lambda expressions,  and other local functions.

Mention a difference between the output parameters and the reference parameters.

Output parameters transfer data out of the method, whereas the reference parameters transfer into it.

When are output parameters beneficial?

Output parameters are beneficial when we need to return values from a function through the parameters without assigning any initial value to the parameter.

What is the "Main" function in C#?

The "Main" function in C#  is the program's starting point, which the run time calls when executing the program.

Conclusion

Functions in C# are essential for creating modular, maintainable, and reusable code. They enable developers to encapsulate logic into named blocks, making code easier to understand and debug. With features like method overloading and the use of lambda expressions, functions in C# offer flexibility and power.

We hope that this blog has helped you enhance your knowledge regarding the functions in C# and if you would like to learn more, check out our articles on Loops in C#

Live masterclass