Non-local methods (regular methods)
A non-local method is a method declared directly inside a type such as a class, struct, record, or interface.
Example:
{
public static int Add(int x, int y) // non-local method
{
return x + y;
}
}
Characteristics:
- Member of a type (class, struct, etc.)
- Accessible according to access modifiers (public, private, etc.)
- Exists independently of another method
- Can be called from other methods
Local methods (local functions)
A local method (officially called local function in C#) is declared inside another method.
Example:
{
static void Main()
{
int Add(int x, int y) // local function
{
return x + y;
}
Console.WriteLine(Add(10, 20));
}
}
Characteristics:
- Declared inside another method
- Scope limited to enclosing method
- Cannot have access modifiers (public, private, etc.)
- Can access local variables of outer method.
- Local methods can be called by its immediate outer method.
Another Example:
{
int bonus = 10;
int AddBonus(int x)
{
return x + bonus; // captures local variable
}
Console.WriteLine(AddBonus(20)); // 30
}
Inside Top-level statements, all methods are local methods.
Example: The following code is in Program file which is a top level statements file.
void Print()
{
Console.WriteLine("Local");
}
👉The compiler transforms top-level code into something similar to:
{
static void Main(string[] args)
{
Console.WriteLine("Hello");
void Print()
{
Console.WriteLine("Local");
}
}
}
So methods declared in top-level statements become local functions inside the compiler-generated Main() method.
How Local methods are called?
{
Console.WriteLine("Hello Outermost");
Outer();
void Outer()
{
Console.WriteLine("Hello Outer");
Print();
void Print()
{
Console.WriteLine("Hello Local");
}
Print();
}
}
Outermost();
Summary
| Feature | Non-local method | Local method |
| Declared inside | Class/Struct | Another method |
| Is type member? | Yes | No |
| Access modifiers allowed | Yes | No |
| Scope | Whole type | Enclosing method only |
| Can access outer locals | No | Yes |
| Example | class A { void RegularM(){} } | void OuterM(){ void InnerM(){} } |
In short:
Non-local methods are members of a class/struct, whereas local methods are declared inside another method and are not type members. Local methods are always implicitly private to its containing outer method.
No comments:
Post a Comment