6

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.

Community
  • 1
  • 1
Rik De Peuter
  • 703
  • 2
  • 9
  • 24

3 Answers3

15

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

Try:

public static class TExtensions
{
  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());
  }
}
devdigital
  • 34,151
  • 9
  • 98
  • 120
0

You have not actually created generic methods you have declared non geeneric methods that return List<T> without defining T. You need to change as below:

public static class TExtensions
    {
        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());
        }
    }
Ben Robinson
  • 21,601
  • 5
  • 62
  • 79