- C# 7 and .NET Core 2.0 Blueprints
- Dirk Strauss Jas Rademeyer
- 244字
- 2025-02-25 23:58:45
Local functions
This is one of those features in C# 7 that I truly wondered where I would ever find a use for. As it turns out, local functions are extremely useful indeed. Also called nested functions by some, these functions are nested within another parent function. It is obviously only within scope inside the parent function and adds a useful way to call code that otherwise wouldn't have any real purpose outside the parent function. Consider the PopulateStorageSpacesList() method:
private void PopulateStorageSpacesList() { List<KeyValuePair<int, string>> lstSpaces =
new List<KeyValuePair<int, string>>(); BindStorageSpaceList((int)StorageSpaceSelection.NoSelection,
"Select Storage Space"); void BindStorageSpaceList(int key, string value)
// Local function { lstSpaces.Add(new KeyValuePair<int, string>(key, value)); } if (spaces is null || spaces.Count() == 0) // Pattern matching { BindStorageSpaceList((int)StorageSpaceSelection.New, "
<create new>"); } else { foreach (var space in spaces) { BindStorageSpaceList(space.ID, space.Name); } } dlVirtualStorageSpaces.DataSource = new
BindingSource(lstSpaces, null); dlVirtualStorageSpaces.DisplayMember = "Value"; dlVirtualStorageSpaces.ValueMember = "Key"; }
To see how PopulateStorageSpacesList() calls the local function BindStorageSpaceList(), have a look at the following screenshot:

You will notice that the local function can be called from anywhere within the parent function. In this case, the BindStorageSpaceList() local function does not return anything, but you can return whatever you like from a local function. You could just as well have done the following:
private void SomeMethod() { int currentYear = GetCurrentYear(); int GetCurrentYear(int iAddYears = 0) { return DateTime.Now.Year + iAddYears; } int nextYear = GetCurrentYear(1); }
The local function is accessible from anywhere within the parent function.