How to use Yield statement in C#

Posted By  jalpesh On 22 May 2010 06:05:36
emailbookmarkadd commentsprint
No of Views:965
Bookmarked:0 times
Votes:0 times

Introduction

Yield statement is one of most interesting statement in the C# 2.0. I have heard about lot of yield statement but today i have learned about yield statement. Yield statement can be used to return multiple object from a method while retaining its state. You can get item in sequence with help of yield.Let take a simple example to see the power or yield statement.

Let's create one example which will help you the understand how its works Let create a function will return the square each time this function is called.

public static IEnumerable<int> Square(int min, int max)
{
for (int i = min; i < max; i++)
{
yield return i*i;
}
}

 Now each time this method is called it will return the square of current value within a given range and its also maintains the state between calls. Let create for each loop to call the the square function above.

foreach (int i in Square(1, 10))
{
Response.Write(i.ToString() + " ");
}

 And here will be the output in the browser. 

Image Loading

i hope this is help to  you all. enjoy the new keyword "Yield".

Sign Up to vote for this article
Other popular Tips/Tricks
    In this tip, I will explain how to use the BigInteger in C# 4.0.The BigInteger is new data type in .NET 4.0.
    Published Date : 22/Sep/2011
    In this tips,I am going to discuss about two important thing about Split function of String class. Split function of the string class split the string in array of string.
    Published Date : 29/Jul/2011
    The Facebook is very popular and it has great support to other development Languages by Facebook SDKs.In this tips, I going to explain how to upload Videos to Facebook through C# with few lines of code.
    Published Date : 13/Jun/2011
    In this tip, i will share with you , how to format time HH:MM:SS from seconds in C#.
    Published Date : 25/Feb/2011
    Enums in dot net programming is a great facility and we all used it to increase code readability. In earlier version of .NET framework we don’t have any method anything that will check whether a value is assigned to it or not. In C# 4.0 we have new static method called HasFlag which will check that particular value is assigned or not.
    Published Date : 01/Jan/2011
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top