Search code examples
c#generic-collectionsdeferred-execution

Is there a built-in C# type that allows deferred execution, but not casting back to IQueryable?


Is there a recommended built-in type in C# that collections can be converted/cast to that will still allow deferred execution, but not allow the type to be cast back into IQueryable? (Like IEnumerable<T> can in some cases)


Solution

  • A built in type no but it's pretty easy to do :

    public static class Utils
    {
        public static IEnumerable<T> AsDefferedEnumerable<T>(this IQueryable<T> Source)
        {
            foreach (var item in Source)
            {
                yield return item;
            }
        }
    }
    

    This way you're not returning a casted IQueryable (that could be casted back) but creating a new IEnumerable wrapping it , you don't even need a new type at all for that you just end up with an IEnumerable that will itself enumerate the IQueryable as it is enumerated without exposing it.

    Edit : sample of a wrapper object (untested)

    public class HideImplementationEnumerable<T>
    {
    public HideImplementationEnumerable(IEnumerable<T> Source)
    {
        this.Source = Source;
    }
    
    private IEnumerable<T> Source;
    
    public IEnumerable<T> Value
    {
        get
        {
            foreach (var item in Source)
            {
                yield return item;
            }
        }
    }
    }