- C# 7 and .NET Core 2.0 Blueprints
- Dirk Strauss Jas Rademeyer
- 244字
- 2021-08-27 19:55:23
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.
- ThinkPHP 5實戰(zhàn)
- Visual Basic程序開發(fā)(學(xué)習(xí)筆記)
- 無代碼編程:用云表搭建企業(yè)數(shù)字化管理平臺
- Java EE框架整合開發(fā)入門到實戰(zhàn):Spring+Spring MVC+MyBatis(微課版)
- 樂學(xué)Web編程:網(wǎng)站制作不神秘
- OpenStack Cloud Computing Cookbook(Fourth Edition)
- Building an RPG with Unity 2018
- Apache Mahout Clustering Designs
- Asynchronous Android Programming(Second Edition)
- Building Business Websites with Squarespace 7(Second Edition)
- 現(xiàn)代CPU性能分析與優(yōu)化
- 快樂編程:青少年思維訓(xùn)練
- Visual C++程序設(shè)計全程指南
- Splunk Developer's Guide(Second Edition)
- Daniel Arbuckle's Mastering Python