Search code examples
c#.netextension-methods

Extension Method Listed for Non Supported Type. Why?


I've created two extension methods: FilterAnyType that operates on IEnumerable<T>, and FilterMovieType that operates on IEnumerable<Movie>:

public static IEnumerable<T> FilterAnyType<T>(this IEnumerable<T> source, Func<T,bool> predicate)
{
     //code goes here
}

public static IEnumerable<Movie> FilterMovieType<Movie>(this IEnumerable<Movie> source, Func<Movie, bool> predicate)
{
     //code goes here
}

And then, I've created two different lists:

var movies = new List<Movie>();
var customers = new List<Customer>();

As expected, the FilterAnyType method is available for both instances of movie and customers. However, the method FilterMovieType is also available to the customer instance, and I was not expecting that.

I am learning extension methods (hence this practice), and the way I understand it is that the this keyword is used to identify the type of object for which the extended method will be "added" to.

Given that, I'd expect that FilterMovieType would be available only to instances of IEnumerable<Movie>. Why is it also available to IEnumerable<Customer>?

Thanks!


Solution

  • Your second method is still a generic, only you named your param Movie, not T. The Movie defined on FilterMovieType has no relation to actual Movie class, it is just a placeholder. To fix it, remove <Movie> after method name, that is:

    public static IEnumerable<Movie> FilterMovieType(this IEnumerable<Movie> source, Func<Movie, bool> predicate)
    {
         //code goes here
    }