Introduction
When working with collections and data in C#, developers often come across two important keywords: return and yield return. At first glance, both seem to do the same job — sending data back from a method. However, their behavior is completely different, especially when dealing with large datasets, memory optimization, and performance.
Understanding the difference between yield return and return in C# is very important for writing efficient and scalable applications. In this article, we will explain both concepts in simple words, with practical examples and real-world use cases.
What is return in C#?
The return keyword in C# is used to exit a method and send a value back to the caller. Once the return statement is executed, the method stops immediately, and no further code runs inside that method.
In simple terms, return gives the complete result at once.
Example of return
public List<int> GetNumbers()
{
List<int> numbers = new List<int>();
for (int i = 1; i <= 5; i++)
{
numbers.Add(i);
}
return numbers;
}
In this example:
All numbers are created and stored in a list
The full list is returned at once
Memory is used to store all values before returning
What is yield return in C#?
The yield return keyword is used to return elements one at a time instead of returning the entire collection at once.
It is mainly used with IEnumerable or IEnumerator.
In simple words, yield return generates values one by one, only when needed.
Example of yield return
public IEnumerable<int> GetNumbers()
{
for (int i = 1; i <= 5; i++)
{
yield return i;
}
}
In this example:
Values are not stored in a list
Each value is returned one at a time
Memory usage is lower
Key Difference Between yield return and return
| Feature | return | yield return |
|---|---|---|
| Execution | Ends method immediately | Pauses and resumes method |
| Data Return | Returns complete collection | Returns one item at a time |
| Memory Usage | Higher (stores all data) | Lower (lazy loading) |
| Performance | Slower for large data | Better for large datasets |
| Use Case | Small datasets | Large or streaming data |

Join the conversation! Your thoughts help the community grow.