One interesting new feature of the C# 2.0 is the "yield" keyword. Basically it is used to iterate through objects returned by a method. It creates a state engine in IL so you can create methods that retain their state and dont have to go through the pain of maintaining state in your code.
Here is a simple example that demonstrates how yield return can be used to maintain state in a method. Every time you call GetInt() you will receive a new incremented integer.
|
public static IEnumerable<int> GetInt() |
Here's the implementation.
|
class Program public static IEnumerable<int> GetInt() |
Usually, the "yield" keyword will be useful when you implement the GetEnumerator() method of the IEnumerable interface
|
class TestClass: IEnumerable<int> public IEnumerator<int> GetEnumerator() #endregion #region IEnumerable Members IEnumerator IEnumerable.GetEnumerator() #endregion } |
Hopefully, this brief sample has helped you understand the new "yield" keyword and how it can be used.
Until next time,
Happy coding
Felipe AlmeidaPosted Feb 6, 2013, 12:12 PM
Here you can find a pratically example of using yield return: http://economizandobits.blogspot.com.br/2013/02/yield-return.html
Felipe AlmeidaPosted Feb 6, 2013, 12:10 PM
Yield keyword is a very powerfull way to improve some enumerable requests that allow you to work with lazy-load, there is an example that you can improve the code performance by using the yield: <a href="http://economizandobits.blogspot.com.br/2013/02/yield-return.html">http://economizandobits.blogspot.com.br/2013/02/yield-return.html</a>
Lajapathy ArunPosted Sep 24, 2012, 7:37 AM
How to understand practically??
AmitPosted Jun 8, 2007, 5:30 AM
I tried using the yield keyword in vb.net, but i presume that it does not work in vb.net as it works in C#.net. Does VB.net support th yield keyword? Do we have a patch for this?