IEnumerable and IEnumerable(Of T) 2


Quick follow up to my earlier post.  Fixing this issue in C# is even easier because of the existence of iterators. 

        public static IEnumerable<object> Shim(System.Collections.IEnumerable enumerable)
        {
            foreach (var cur in enumerable)
            {
                yield return cur;
            }
        }

Comments (3)

  1. richard_deeming says:

    You can only use "var" if you’re running .NET 3.5; otherwise, you need to use "object". (If you are running 3.5, I believe this method is already included as one of the LINQ extension methods.)

    Sticking with .NET 2.0, if you want a strongly-typed enumerator, or to change the type of an existing IEnumerable<T>, you can use a Converter<TInput, TOutput> delegate:

    public static IEnumerable<T> Shim<T>(IEnumerable enumerable, Converter<object, T> convert)

    {

       foreach (object item in enumerable)

       {

           yield return convert(item);

       }

    }

    public static IEnumerable<TOutput> Shim<TInput, TOutput>(IEnumerable<TInput> enumerable, Converter<TInput, TOutput> convert)

    {

       foreach (TInput item in enumerable)

       {

           yield return convert(item);

       }

    }

  2. Chris says:

    richard_deeming:

    If you set your VS2008 project to target .NET 2.0, you can still get the new language features. `var` and lambdas work for free, and you can get extension methods working by defining a single tiny class (ExtensionAttribute)

Skip to main content