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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With