Yield is something I find tough to understand till now. But now I am getting a hold of it. Now, in a project, if I return List, Microsoft code analysis will give a warning about it. So, normally I'll do all the necessary logical parts and return the list as IEnumerable. I want to know the difference between the two. Means if I am doing yield return or otherwise.
Here is a very simple example I am showing, normally the code is a little bit complicated.
private static IEnumerable<int> getIntFromList(List<int> inputList)
{
var outputlist = new List<int>();
foreach (var i in inputList)
{
if (i %2 ==0)
{
outputlist.Add(i);
}
}
return outputlist.AsEnumerable();
}
private static IEnumerable<int> getIntFromYeild(List<int> inputList)
{
foreach (var i in inputList)
{
if (i%2 == 0)
{
yield return i;
}
}
}
One significant benefit I can see is fewer lines. But is there any other benefit? Should I change and update my functions which are returning IEnumearble to use yield instead of List? What is the best way or a better way to do things?
Here, I can use simple lambda expressions over List, but normally that is not the case, this example is specifically to understand best approach of coding.