What are the advantages of local C # 7 functions over lambdas?

The other day, in one of my utilities, ReSharper hinted to me a piece of code that says that the lambda that defines the ThreadStart delegate can be turned into a local function:

 public void Start(ThreadPriority threadPriority = ThreadPriority.Lowest) { if (!Enabled) { _threadCancellationRequested = false; ThreadStart threadStart = () => NotificationTimer (ref _interval, ref _ignoreDurationThreshold, ref _threadCancellationRequested); Thread = new Thread(threadStart) {Priority = ThreadPriority.Lowest}; Thread.Start(); } } 

And, therefore, it is converted to:

 public void Start(ThreadPriority threadPriority = ThreadPriority.Lowest) { if (!Enabled) { _threadCancellationRequested = false; void ThreadStart() => NotificationTimer(ref _interval, ref _ignoreDurationThreshold, ref _threadCancellationRequested); Thread = new Thread(ThreadStart) {Priority = ThreadPriority.Lowest}; Thread.Start(); } } 

What are the advantages of the latter compared to the former, is it only about performance?

I already checked the resources below, but in my example the benefits are not so obvious:

+5
source share
1 answer

The first website you linked mentions some of the benefits of local functions:
- Lambda causes excretion.
- There is no elegant way to write a recursive lambda.
β€œThey cannot use yield return and possibly some other things.”

One useful use case is iterators:

Wrong:

 public static IEnumerable<T> SomeExtensionMethod<T>(this IEnumerable<T> source) { //Since this method uses deferred execution, //this exception will not be thrown until enumeration starts. if (source == null) throw new ArgumentNullException(); yield return something; } 

The right way:

 public static IEnumerable<T> SomeExtensionMethod<T>(this IEnumerable<T> source) { if (source == null) throw new ArgumentNullException(); return Iterator(); IEnumerable<T> Iterator() { yield return something; } } 
+6
source

Source: https://habr.com/ru/post/1272469/


All Articles