Avatar ·

What is the yield keyword in C# for? How to use yield return and yield break?

Hi everyone! I just started learning C# and came across the `yield` keyword. Honestly, I don't fully understand what it's for and how to use it correctly.\n\nI've seen examples where `yield return` is used inside methods that return `IEnumerable` or `IEnumerable`. But I have two questions:\n\n1. What is the difference between returning a collection normally (e.g., `List` via `return`) and using `yield return`?\n2. When is this actually needed in real projects, not just in tutorial examples?\n\nHere's an example I found on MSDN, but it seems strange to me:\n\n```csharp\nstatic IEnumerable GetNumbers()\n{\n for (int i = 0; i < 10; i++)\n {\n yield return i;\n }\n}\n```\n\nWhy can't we just do this?\n\n```csharp\nstatic List