Skip to content

Instantly share code, notes, and snippets.

@jpaugh
Last active April 17, 2019 14:00
Show Gist options
  • Save jpaugh/f080c9c83add05ec28394be3d24ff8f6 to your computer and use it in GitHub Desktop.
Save jpaugh/f080c9c83add05ec28394be3d24ff8f6 to your computer and use it in GitHub Desktop.
Test whether AsEnumerable differs from casting regarding a hidden extension method.
using System;
using System.Collections.Generic;
using System.Linq;
namespace AsEnumerableVsCasting
{
class AsEnumerableVsCasting
{
static void Main(string[] args)
{
var sneaky = new Sneaky { "a", "b", "c" };
Print(sneaky.Select(s => s)); // prints x, y, z (specialized method; Enumerable.Select is hidden)
Print(sneaky.AsEnumerable().Select(s => s)); // prints a, b, c (generic method Enumerable.Select)
Print(((IEnumerable<string>) sneaky).Select(s => s)); // prints a, b, c (generic method Enumerable.Select)
}
static void Print(IEnumerable<string> list)
{
Console.WriteLine(string.Join(", ", list));
}
}
class Sneaky : List<string>
{
public IEnumerable<TResult> Select<TResult>(Func<string,TResult> project)
{
return (new List<string> { "x", "y", "z" }).Select(project);
}
}
}
@jpaugh
Copy link
Author

jpaugh commented Apr 17, 2019

Turns out, AsEnumerable and casting to IEnumerable<T> work the same way, here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment