Search code examples
c#.netlazy-loadinglazy-evaluationlazy-initialization

c# is it possible to lazy load function parameter after calling the function?


I was wondering if it possible in C# to lazy load the parameter of a function after calling the function. In fact I want the parameter of the function to be loaded only when I use the output of the function. I try to explain what I mean with the following example:

        var a = Enumerable.Range(1, 10);
        int take = 5;
        var lazyTake = new Lazy<int>(() => take);

        // here I still don't iterate on Enumerable, I want the parameter of function Take be initialized later when I start iterating
        var b = a.Take(lazyTake.Value);

        // here I initialize (change) the value of parameter take
        take = 6;   

        Console.WriteLine(b.ToList().Count);  // I want b to have 6 elements but it's 5

Here Lazy<int> is not doing what I need. Does anyone know any workaround or language feature to support such a case?


Solution

  • public static IEnumerable<T> Take<T>(this IEnumerable<T> source, Lazy<int> count) { 
        var takeSequence = source.Take(count.Value);
        foreach (var item in takeSequence) yield return item;
    }
    

    This is fully lazy. The body of this function will only execute when you start enumerating because this is an iterator method. Only then will the lazy count be forced to materialize.

    Instead of a Lazy you could pass a Func<int> getTakeCount parameter as well.