When writing code in C# or learning about methods in programming, you may be wondering if we can create a method inside another method in C#. In this blog, I discuss how we can create a method inside another method in a C# program.
Introduction
Creating a method inside another method is called local functions in C#.
- Using a method inside another method makes code easier to read. Local functions is just like lamda expressions.
- Local function is a private method.
- We can declare local functions inside methods, constructors, anonymous methods, lambda expressions and other local functions.
- We can write a local function as generic.
- We can use out and ref parameters in location functions.
- We can use params in local functions.
- We can create multiple local functions inside a method.
- Local functions do not allow access modifiers
Local Function Syntax
- <modifiers> <return-type> <method-name> <parameter-list>
Below example provides information has to ow we can create multiple local functions. Here the Main is the method and inside that we have created Sum, Sub, Mul local functions.
- using System;
- namespace LocalFunctions
- {
- class Program
- {
- static void Main(string[] args)
- {
- Console.WriteLine($"Sum: {Sum(10, 20)}");
- Console.WriteLine($"Sub: {Sub(10, 20)}");
- Console.WriteLine($"Mul: {Mul(10, 20)}");
- Console.WriteLine($"Sum: {Sum(5, 15)}");
- int Sum(int a, int b)
- {
- return a + b;
- }
- int Sub(int a, int b)
- {
- return a - b;
- }
- int Mul(int a, int b)
- {
- return a * b;
- }
- Console.ReadKey();
- }
- }
- }
Output
- Sum: 30
- Sub: -10
- Mul: 200
- Sum: 20

Join the conversation! Your thoughts help the community grow.