A simple representation of the difference between "yield return" and "return" statement.
This post is about the difference between 'yield' and 'return' statement. Yield and return look similar but they are different. Most of the people think the two terms to be one and the same.Understanding the difference can help us to understand the use and importance of 'yield' keyword.
A Short Intro about yield
The 'yield' keyword is used when implementing Enumerators.
The syntax of yield statement is as follows:
yield return <expression>;
The yield keyword was introduced in C# 2.0 (it is not currently available in VB.NET) and is useful for iteration. It returns the next item in the sequence.
What I though is to give an example instead of writing a long description as understanding the example will give a basic knowledge about
Lets assume that we have 2 functions. One function is with return statement and another one which has yield return statement.
Function with 'return' statement
public string ReturnFunction()
{
return "Function Call 1 <br/>";
return "Function Call 2 <br/>";
return "Function Call 3 <br/>";
}
Function with 'yield return'
public IEnumerable<string> YieldFunction()
{
yield return "Function Call 1 <br/>";
yield return "Function Call 2 <br/>";
yield return "Function Call 3 <br/>";
}
Now here the return type should be of type Enumerators or else 'yield return' can not be implemented.
Event handler for function with return statement
protected void btnReturn_Click(object sender, EventArgs e)
{
// Calling Function 3 times
string displayText = ReturnFunction() + ReturnFunction() + ReturnFunction();
lblDisplay.Text = String.Empty;
lblDisplay.Text = displayText;
}
Event handler for function with yield return statement
protected void btnYield_Click(object sender, EventArgs e)
{
//First Call
IEnumerable<string> x = YieldFunction();
//Secend Call
x.Concat(YieldFunction());
//Third Call
x.Concat(YieldFunction());
List<string> y = x.ToList();
lblDisplay.Text = String.Empty;
foreach (var i in y)
{
lblDisplay.Text += i;
}
}
Now when we click the button to handle ReturnFunction() method then the following output comes on the screen.
Now check that though the function ReturnFunction() has the 3 return statements but return statement does not keep the state of it's last return. So it always executes the first return.
Interesting thing happens when we click the button for yield return. 'Yield Return' keeps the state of last return and returns the next item in the sequence.
Does that give an idea?