X

Local functions in C#

Csharp-MS-Dotnet

In C# 7 there the new feature called Local functions in C#. Basically Local functions allow one to write a function within the body of another method or function. It comes in handly in the case lets say you are creating a helper function that are mostly just used in one class or where the declaration makes the code clear of the intention. Local functions also come in handly to write recursive functions rather than using a Lambda for it.

Here are some places where you can use local functions.

  • Methods, especially iterator methods and async methods
  • Constructors
  • Property accessors
  • Event accessors
  • Anonymous methods
  • Lambda expressions
  • Finalizers
  • Other local functions

Below is an example where I Anonymize a string of emails, you can see that I am actually calling the local function below the return statement. Therefore where you can declare a local function below a return statement and also the Pattern variable is available inside the local function, since it is within its scope.

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace Mask
{
    class Program
    {
        static void Main(string[] args)
        {         
            Console.WriteLine(string.Join(",", AnonymizeEmail()));
            //output will look like this
            //p***r@a**.com,t****r@g****.com

        }

        private static IEnumerable AnonymizeEmail()
        {
            var emails = new List { "peter@abc.com", "taswar@gmail.com"};

            const string PATTERN = @"(?();
            foreach(var email in emails)
            {
                result.Add(MaskEmail(email));
            }

            return result;

            string MaskEmail(string s)
            {
                if (!s.Contains("@"))
                    return new String('*', s.Length);
                if (s.Split('@')[0].Length  new string('*', m.Length));
            }                    
        }
    }    
}

If you wish to read more on local functions take a look at the Microsoft documentation of local functions.

Categories: .NET C#
Tags: csharpdotnet
Taswar Bhatti:
Related Post