Table of contents
1.
Introduction
2.
Local Functions in C#
3.
Key Points About Local Functions
4.
Example
5.
Advantages of Local Functions
5.1.
Local generic functions are permitted.
5.2.
You can use parameters in local functions.
6.
Frequently Asked Questions
6.1.
What are the different types of functions in C#?
6.2.
Are functions called methods in C#?
6.3.
What is the difference between function and method?
7.
Conclusion
Last Updated: Mar 27, 2024

Local Functions in C#

Author Sanjana Yadav
0 upvote

Introduction

In earlier articles, we learned that methods and properties in C# belong to classes. Local variables, which are exclusively available inside the scope of this specific method, can be used within methods. This makes sense since you'll frequently need to keep temporary data that shouldn't be available from other classes or even other methods within the same class. Previously, if a method was declared on a class, it could only be accessed from other methods within the same class, but in C# version 7, the idea of local functions was introduced.

Local Functions in C#

C# 7.0 introduces the local function feature. It enables you to declare a method within the body of another method that has already been declared. In other terms, a local function is a private function of a function that has a scope confined to the function in which it is defined. The type of local function is the same as the type of function that defines it. Local functions can only be called from their container members.

Local functions are used to make code more legible and straightforward.

Local functions can be declared in the following scope.

  • Methods
  • Constructors
  • Property accessors
  • Event accessors
  • Anonymous methods
  • Lambda expressions
  • Finalizers
  • Other local functions

Key Points About Local Functions

  • You can use async and unsafe modifiers in local functions.
  • Local functions have access to the container method's local variables, including method parameters.
  • You are not permitted to use any member access modifiers, including the private keyword, in the local function definition since they are private, and you are not permitted to make them public.
  • You may not additionally use the static keyword with a local function.
  • It is also forbidden to apply attributes to the local function, its parameters, or its parameter type.
  • It is possible to have many local functions.
  • Local functions are not permitted to be overloaded.

Example

using System;
public class ExampleProgram {
    // Main method
    public static void Main()
    {
        // Local Function
        void LocalFunction(int x, int y)
        {
            Console.WriteLine("Value of x is: " + x);
            Console.WriteLine("Value of y is: " + y);
            Console.WriteLine("Sum of x and y is: {0}", x + y);
            Console.WriteLine();
        }
        // Calling Local function
        LocalFunction(12, 10);
        LocalFunction(40, 30);
    }
}

Output

Value of x is: 12
Value of y is: 10
Sum of x and y is: 22

Value of x is: 40
Value of y is: 30
Sum of x and y is: 70

Advantages of Local Functions

Local generic functions are permitted.

Example

using System;
public class ExampleProgram {
// Main method
public static void Main()
{
// Local Function with out parameter
void LocalFunction(string str, out string s)
{
s = str + "Learn"
+ "Grow";
}
string x = null;
// Calling Local function
LocalFunction("Ninjas!!", out x);
Console.WriteLine(x);
}
}

Output

LearnGrowNinjas!!

You can use parameters in local functions.

Example

using System;
public class ExampleProgram {
    public static void Main()
    {


        // Local Function
        // Using params
        void LocalFunctions(params string[] chars)
        {
            for (int x = 0; x < chars.Length; x++)
            {
                Console.WriteLine(chars[x]);
            }
        }
        // Calling Local function
        LocalFunctions("Learn", "Code", "CodingNinjas", "1234CN");
    }
}

Output

Learn
Code 
CodingNinjas
1234CN

Frequently Asked Questions

What are the different types of functions in C#?

Pure virtual method, Virtual method, Abstract method, Partial method, Extension method, Instance method, Static method.

Are functions called methods in C#?

To execute the function, you must call it in the Main() method after it has been created. To call a method, first, construct an object of the contained class, then call the method using the dot(.) operator. If a method is static, there is no need to build an object; simply call it followed by the class name.

What is the difference between function and method?

The phrases method and function are interchangeable. In object-oriented programming, a method is a process or function. A function is a collection of reusable code that may be invoked from anywhere in your application. This avoids the need to write the same code again and over.

Recommended Topic -  singleton design pattern in c#

Conclusion

In this article, we have extensively discussed the Local functions in C# with examples.

We hope that this blog has helped you enhance your knowledge of the functions in C#, and if you would like to learn more about C#, check out our articles C# | Learn & Practice from Coding Ninjas Studio.

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio! But if you have just started your learning process and are looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc., you must look at the problemsinterview experiences, and interview bundle for placement preparations.

Nevertheless, you may consider our paid courses to give your career an edge over others!

Do upvote our blogs if you find them helpful and engaging!

Happy Learning!

Live masterclass