yield-return

C# - Proper Use of yield return

The yield keyword is one of those keywords in C# that continues to mystify me and I've never been confident that I'm using it correctly. Of the following two pieces of code, which is the preferred and why? Version 1: Using yield return public static IEnumerable<Product> GetAllProducts() { using (AdventureWorksEntities db = new Adv...

Can I implement yield return for IEnumerable functions in VB.NET?

In C#, when writing a function that returns an IEnumerble<>, you can use yield return to return a single item of the enumeration and yield break; to signify no remaining items. What is the VB.NET syntax for doing the same thing? An example from the NerdDinner code: public IEnumerable<RuleViolation> GetRuleViolations() { if (String...

What is the purpose/advantage of using yield return iterators in C#?

All of the examples I've seen of using yield return x; inside a C# method could be done in the same way by just returning the whole list. In those cases, is there any benefit or advantage in using the yield return syntax vs. returning the list? Also, in what types of scenarios would yield return be used that you couldn't just return the...

How does the NerdDinner example's Dinner.GetRuleViolations function return a list?

From what I've read, yield return <value> jumps out of the function the moment the line is executed. However, Scott Guthrie's text indicates that var errors = dinner.GetRuleViolations(); successfully pulls out a list of all the rule violations even though GetRuleViolations is a long list of if(String.someFunction(text)) yield ...

In C#, why can't an anonymous method contain a yield statement?

I thought it would be nice to do something like this (with the lambda doing a yield return): public IList<T> Find<T>(Expression<Func<T, bool>> expression) where T : class, new() { IList<T> list = GetList<T>(); var fun = expression.Compile(); var items = () => { foreach (var item in list) if (fun.Invoke(i...

Nested yield return with IEnumerable

I have the following function to get validation errors for a card. My question relates to dealing with GetErrors. Both methods have the same return type IEnumerable<ErrorInfo>. private static IEnumerable<ErrorInfo> GetErrors(Card card) { var errors = GetMoreErrors(card); foreach (var e in errors) yield return e; /...

Is yield return in C# thread-safe?

I have the following piece of code: private Dictionary<object, object> items = new Dictionary<object, object>; public IEnumerable<object> Keys { get { foreach (object key in items.Keys) { yield return key; } } } Is this thread-safe? If not do I have to put a lock around the loop or the y...

yield return statement inside a using() { } block Disposes before executing

I've written my own custom data layer to persist to a specific file and I've abstracted it with a custom DataContext pattern. This is all based on the .NET 2.0 Framework (given constraints for the target server), so even though some of it might look like LINQ-to-SQL, its not! I've just implemented a similar data pattern. See example be...

What is the difference (if any) between "yield" and "yield return" in C#?

I've traditionally used yield in C# without the return, e.g.: IEnumerable<T> Foobar() { foreach( var foo in _stuff ) { yield foo; } } But in other examples I've seen it written as "yield return foo;", see: http://msdn.microsoft.com/en-us/library/9k7k7cf0%28VS.80%29.aspx. Is there any difference? ...

Is there a Java equivalent to C#'s 'yield' keyword?

I know there is no direct equivalent in Java itself, but perhaps a third party? It is really convenient. Currently I'd like to implement an iterator that yields all nodes in a tree, which is about five lines of code with yield. ...

Recursive Linq Function and Yielding

public static IEnumerable<UIElement> Traverse(this UIElementCollection source) { source.OfType<Grid>().SelectMany(v => Traverse(v.Children)); //This is the top level. foreach (UIElement item in source) { yield return item; } } This never returns anything recursively. I have b...

Implementing yield (yield return) using Scala continuations

How might one implement C# yield return using Scala continuations? I'd like to be able to write Scala Iterators in the same style. A stab is in the comments on this Scala news post, but it doesn't work (tried using the Scala 2.8.0 beta). Answers in a related question suggest this is possible, but although I've been playing with delimited...

Using IEnumerable without foreach loop

I've gotta be missing something simple here. Take the following code: public IEnumerable<int> getInt(){ for(int i = 0; i < 10; i++){ yield return i; } } I can call this with: foreach (int j in obj.getInt()){ //do something with j } How can I use the getInt method without the foreach loop: IEnumerable<int> iter = obj.getI...

Can you yield return into an IList<T>?

In my service layer for my MVC application I am attempting to convert the linq to sql entity results into my business model entities. I am currently attempting the following code: public IList<Project> GetAllProjects() { var results = from p in _context.Repository<DBMappings.project>() select p; ...

Method not called when using yield return

Hi, I'm having a little trouble with a method in which I use yield return this doesn't work... public IEnumerable<MyClass> SomeMethod(int aParam) { foreach(DataRow row in GetClassesFromDB(aParam).Rows) { yield return new MyClass((int)row["Id"], (string)row["SomeString"]); } } The above code never runs, when th...

ControlCollection extension method optimization

Hi, got question regarding an extension method that I have written that looks like this: public static IEnumerable<T> FindControlsOfType<T>(this ControlCollection instance) where T : class { T control; foreach (Control ctrl in instance) { if ((control = ctrl as T) != null) { yield return control...

How to handle an "infinite" IEnumerable?

A trivial example of an "infinite" IEnumerable would be IEnumerable<int> Numbers() { int i=0; while(true) { yield return unchecked(i++); } } I know, that foreach(int i in Numbers().Take(10)) { Console.WriteLine(i); } and var q = Numbers(); foreach(int i in q.Take(10)) { Console.WriteLine(i); } both work fine (and ...

yield returns within lock statement

Hi eveybody, if i have a yield return in a lock statement does the lock get taken out on each yield (5 times in the example below) or only once for all the items in the list? Thanks private List<string> _data = new List<string>(){"1","2","3","4","5"}; private object _locker =new object(); public IEnumerable<string> GetData(...

Problem with debug watch in Visual Studio with yield return enumerator methods

I have a method which returns an IEnumerable<> which it builds up using the yield return syntax: namespace Validation { public class UserValidator { public IEnumerable<ValidationError> Validate(User user) { if (String.IsNullOrEmpty(user.Name)) { yield return new ValidationE...

Is this a dangerous locking pattern?

I have an enumerator written in C#, which looks something like this: try { ReadWriteLock.EnterReadLock(); yield return foo; yield return bar; yield return bash; } finally { if (ReadWriteLock.IsReadLockHeld) ReadWriteLock.ExitReadLock(); } I believe this may be a dangerous locking pattern, as the ReadWriteLo...