SuperLinq SuperLinq
SuperLinq SuperLinq
DocFX + Singulink = ♥

Search Results for

    Method Using

    | Edit this page

    Using<TSource, TResource>(Func<TResource>, Func<TResource, IEnumerable<TSource>>)

    Generates a sequence that's dependent on a resource object whose lifetime is determined by the sequence usage duration.

    Declaration
    public static IEnumerable<TSource> Using<TSource, TResource>(Func<TResource> resourceFactory, Func<TResource, IEnumerable<TSource>> enumerableFactory) where TResource : IDisposable
    Parameters
    Type Name Description
    Func<TResource> resourceFactory

    Resource factory function.

    Func<TResource, IEnumerable<TSource>> enumerableFactory

    Enumerable factory function, having access to the obtained resource.

    Returns
    Type Description
    IEnumerable<TSource>

    Sequence whose use controls the lifetime of the associated obtained resource.

    Type Parameters
    Name Description
    TSource

    Source element type.

    TResource

    Resource type.

    Remarks

    resourceFactory and enumerableFactory are evaluated lazily, once enumeration has begun. The value returned by resourceFactory will be disposed after the enumeration has completed.

    The values returned by enumerableFactory and enumerableFactory are not cached; multiple iterations of the IEnumerable<T> returned by this method will call these methods separately for each iteration.

    Examples

    The following code example demonstrates how to create a sequence that throws on enumeration using Using.

    var sequence = Enumerable.Range(1, 10);
    
    // Hold a resource for the duration of an enumeration
    var result = SuperEnumerable
        .Using(
            () => new DummyDisposable(),
            d => d.GetValues())
        .Do(x => Console.Write($"{x}, "));
    
    Console.WriteLine(
        "[" +
        string.Join(", ", result) +
        "]");
    
    // This code produces the following output:
    // Constructor
    // GetValues
    // 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 
    // Dispose
    // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    
    class DummyDisposable : IDisposable
    {
        public DummyDisposable()
        {
            Console.WriteLine("Constructor");
        }
    
        public IEnumerable<int> GetValues()
        {
            Console.WriteLine("GetValues");
            return Enumerable.Range(1, 10);
        }
        
        public void Dispose()
        {
            Console.WriteLine();
            Console.WriteLine("Dispose");
        }
    }
    
    Exceptions
    Type Condition
    ArgumentNullException

    resourceFactory or enumerableFactory is null.

    © SuperLinq Authors. All rights reserved.