Passing interface as a parameter to an extension method

I have used extension methods to extend html helpers to make an RSS repeater:

    public static string RSSRepeater(this HtmlHelper html, IEnumerable<IRSSable> rss)
        string result="";

        foreach (IRSSable item in rss)
            result += "<item>" + item.GetRSSItem().InnerXml + "</item>";

        return result;

So I make one of my business objects implement IRSSable, and try to pass this to the HTML helper. But I just cannot seem to make it work, I have tried:

<%=Html.RSSRepeater(ViewData.Model.GetIssues(null, null, "") as IEnumerable<IRSSable>) %>

Compiles fine, but null is passed

<%=Html.RSSRepeater(ViewData.Model.GetIssues(null, null, "")) %>

Intellisense moans about not being able to pass IEnumerable issue to IEnumberable IRSSable

  • So how do you do it? That method I am calling definitly returns IEnumberable<Issue> and Issue definitly implements IRSSAble


Ahh... try:

 public static string RSSRepeater<T>(this HtmlHelper html, IEnumerable<T> rss)
     where T : IRSSable

This then should allow you to pass any sequence of things that implement IRSSable - and the generic type inference should mean you don't need to specify the T (as Issue) yourself - the compiler will handle it.

By the way - avoid concatenation here; StringBuilder is preferable:

    StringBuilder result = new StringBuilder();

    foreach (IRSSable item in rss)

    return result.ToString();

Need Your Help

Select and Group by together

sql group-by db2

I have my query like this:

Find text from a file and set it as a variable in applescript?


I am trying to build a script that sends me updates and notifications from Please keep on reading below, so I may guide you until the point I have trouble with.