Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding generic extension methods to interfaces like IEnumerable

I've been trying and trying to make my generic extension methods work, but they just refuse to and I can't figure out why. This thread didn't help me, although it should.

Of course I've looked up how to, everywhere I see they say it's simple and it should be in this syntax:
(On some places I read that I need to add "where T: [type]" after the parameter decleration, but my VS2010 just says that's a syntax error.)

using System.Collections.Generic;
using System.ComponentModel;

public static class TExtensions
{
    public static List<T> ToList(this IEnumerable<T> collection)
    {
        return new List<T>(collection);
    }

    public static BindingList<T> ToBindingList(this IEnumerable<T> collection)
    {
        return new BindingList<T>(collection.ToList());
    }
}

But that just doesn't work, I get this error:

The type or namespace name 'T' could not be found (are you missing a using directive or an assembly reference?)

If I then replace

public static class TExtensions

by

public static class TExtensions<T>

it gives this error:

Extension method must be defined in a non-generic static class

Any help will be much appreciated, I'm really stuck here.

like image 978
Rik De Peuter Avatar asked Jun 21 '11 09:06

Rik De Peuter


1 Answers

I think what you're missing is making the methods generic in T:

public static List<T> ToList<T>(this IEnumerable<T> collection)
{
    return new List<T>(collection);
}

public static BindingList<T> ToBindingList<T>(this IEnumerable<T> collection)
{
    return new BindingList<T>(collection.ToList());
}

Note the <T> after the name of each method, before the parameter list. That says it's a generic method with a single type parameter, T.

like image 166
Jon Skeet Avatar answered Oct 20 '22 09:10

Jon Skeet