I’m currently experimenting with extension methods. My goal is a extension method for List which finds the first element that fits the given element in a collection, after a specified index.
public static class Extensions
{
public static T FindFirstAfterIndex<T>(this List<T> list, int index, T item) where T : class where T : struct
{
return list.Skip<T>(index).Where<T>(result => result == item).First<T>();
}
}
so this works for class objects as T.
I also tried:
public static T FindFirstAfterIndex<T>(this List<T> list, int index, T item) where T : class
where T : struct
{
return list.Skip<T>(index).Where<T>(result => result == item).First<T>();
}
I’m very new in the generic stuff an T so how can i define my where clause to accept also List<int> ?
regards Mark
Your extension method in invalid in terms of its constraints:
(The
where T : structconstraint is scrolled all the way over to the right on your question.)You can’t specify two constraint clauses for the same type parameter like this. You can specify one constraint clause with multiple constraints (e.g.
where T : class, IDisposable), but it can’t include both theclassandstructconstraints.If your extension method really only has one constraint and that constraint is
where T : class, then that explains why it’s not valid forList<int>– becauseintdoesn’t satisfy the reference type constraint.Frankly your method would be better off written like this:
Now it will work for any list, and will use the default equality semantics of
T(which will make it work more conventionally forList<string>for example) and also allow you to supply a custom equality comparer when you want to.