Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

yield return vs Lazy<T>

Tags:

c#

.net

I've learnt about lazy execution with yield return. Now I've seen a type which was introduced in .Net 4 (Lazy<T>). My question is: Is there any connection between these? I've checked the methods of Lazy<T> in ILSpy, but I haven't seen method implementation with yield return. So are they connected at lower levels?

like image 817
speti43 Avatar asked Dec 02 '22 19:12

speti43


2 Answers

They have nothing to do with each-other.

Iterator methods (methods which use yield return, such as LINQ methods) used deferred execution.
That means that the code in the method will not run until you enumerate its results.

Lazy<T> is a wrapper that will only compute its value when the Value property is first accessed.

like image 56
SLaks Avatar answered Dec 15 '22 02:12

SLaks


No, they has nothing to do with each other .

yield is used to return current pointer to an object during iteration. It's very useful on iterating over large data sets and filtering/validating... some data contemporary (during iteration), so you don't need to cache filtered (say) values first, as it will make memory grow unreasonably big.

Lazy, is about a late/lazy or defered initialization, instead . It's all about late intialization of an instance of a type you specify like such.

Example: you have a type, that on initilization allocates a lot of memory, but it's very common case in your application workflow that user will not need that type (some specific, user requested operation), so you use Lazy<T>, to define a type, but do not initialize it, so allocate memory only when it actually needed.

You can see that there is no any relation between these concepts.

like image 23
Tigran Avatar answered Dec 15 '22 02:12

Tigran