In C# 7.0, they provided a new feature called local function. If you want to reuse the set of codes within the function, it will be useful.
To learn about the local function, refer to this URL.
The sample code for local function is given below.
- static void Main(string[] args) {
- int ShowMessage() {
- Console.WriteLine("The message from local function.");
- }
- ShowMessage();
- Console.ReadKey();
- }
Characteristics and rule of local function
- The local function is capable of accessing the parameter and local variable of the parent function.
- If you want access the local variable into the local function, it should be declared before local function definition.
- The local functions should be declared before calling it.
- All other characteristics of the function are applicable to the local function.
Thus, if you want to achieve this feature on older versions of C# 7.0, you can do it, using a delegate, as shown below.
- static void Main(string[] args) {
- MethodRef localMethod = new MethodRef(delegate() {
- Console.WriteLine("The message from local function.");
- });
- localMethod();
- Console.ReadKey();
- }
Please feel free to ask any questions regarding local function. You can share, if you know anything about local function usage.