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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
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<string> AnonymizeEmail() { var emails = new List<string> { "peter@abc.com", "taswar@gmail.com"}; const string PATTERN = @"(?<=[\w]{1})[\w-\._\+%\\]*(?=[\w]{1}@)|(?<=@[\w]{1})[\w-_\+%]*(?=\.)"; var result = new List<string>(); 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 < 4) return @"*@*.*"; return Regex.Replace(s, PATTERN, m => new string('*', m.Length)); } } } } |
If you wish to read more on local functions take a look at the Microsoft documentation of local functions.
Leave A Comment