Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is yield useful outside of LINQ?

Tags:

yield

c#

.net

linq

When ever I think I can use the yield keyword, I take a step back and look at how it will impact my project. I always end up returning a collection instead of yeilding because I feel the overhead of maintaining the state of the yeilding method doesn't buy me much. In almost all cases where I am returning a collection I feel that 90% of the time, the calling method will be iterating over all elements in the collection, or will be seeking a series of elements throughout the entire collection.

I do understand its usefulness in linq, but I feel that only the linq team is writing such complex queriable objects that yield is useful.

Has anyone written anything like or not like linq where yield was useful?

like image 220
Bob Avatar asked Nov 25 '08 15:11

Bob


People also ask

When should I use yield in C#?

You use a yield return statement to return each element one at a time. The sequence returned from an iterator method can be consumed by using a foreach statement or LINQ query. Each iteration of the foreach loop calls the iterator method.

What is the yield keyword used for?

The yield keyword is use to do custom stateful iteration over a collection. The yield keyword tells the compiler that the method in which it appears is an iterator block. yield return <expression>; yield break; The yield return statement returns one element at a time.

What does C# Yield do?

The yield keyword performs custom and stateful iteration and returns each element of a collection one at a time sans the need of creating temporary collections. The yield keyword, first introduced in C# 2.0, T returns an object that implements the IEnumerable interface.

Is yield return thread safe?

As written it is thread safe but if you comment out the lock(_sync) in AllValues you should be able to verify that it is not thread safe by running it a few times.


1 Answers

Note that with yield, you are iterating over the collection once, but when you build a list, you'll be iterating over it twice.

Take, for example, a filter iterator:

IEnumerator<T>  Filter(this IEnumerator<T> coll, Func<T, bool> func) {      foreach(T t in coll)         if (func(t))  yield return t; } 

Now, you can chain this:

 MyColl.Filter(x=> x.id > 100).Filter(x => x.val < 200).Filter (etc) 

You method would be creating (and tossing) three lists. My method iterates over it just once.

Also, when you return a collection, you are forcing a particular implementation on you users. An iterator is more generic.

like image 172
James Curran Avatar answered Oct 20 '22 18:10

James Curran