I am quite new to c sharp.In order to grasp the idea about generic,callback and extension methods i've comp up with the following example.The extension method i wrote will operate on a IEnumerable type and will accept a callback and a integer parameter "year".It will filter out the IEnumerable and return only the item which will pass the test.But while executing the program i've encountered some error :
The type argument for the extension method can not be inferred from the usage
and for the "return item " inside extension method i am getting error : can not implicitly convert type T to System.Collections.Generic.IEnumerable .An explicit conversion exists.
class Program
{
static void Main(string[] args)
{
List<Students> students = new List<Students>();
students.Add(new Students("zami", 1991));
students.Add(new Students("rahat", 2012));
students.FilterYear((year) =>
{
List<Students> newList = new List<Students>();
foreach (var s in students)
{
if (s.byear >= year)
{
newList.Add(s);
}
}
return newList;
}, 1919);
}
}
public static class LinqExtend
{
public static IEnumerable<T> FilterYear<T>(this IEnumerable<T> source, Func<int, T> callback, int year)
{
var item = callback(year);
return item;
}
}
public class Students
{
public string name;
public int byear;
public Students(string name, int byear)
{
this.name = name;
this.byear = byear;
}
}
IEnumerable<T>given the function - Nkosi