Search code examples
c#linq-to-sqlinterfacepolymorphismcovariance

Passing different content that implements the same interface


I have multiple Linq2Sql Classes such as "Article" "NewsItem" "Product".

They all have a title, they all have a unique ID and they all have a Summary.

So, I created an interface called IContent

public interface IContent {
    int Id { get; set; }
    String Title { get; set; }
    String Summary { get; set; }
    String HyperLink { get; set; }
}

In my code, I'm trying to make it possible to pass a List<T> that implements IContent and then use those common properties that I have implemented in each of the partial classes in my project.

So, just to clarify

Article is a Linq Entity. I create a partial class and implement IContent Here's a snippet of Article.cs:

   #region IContent Members

    public int Id {
        get {
            return this.ArticleID;
        }
        set {
            this.ArticleID = value;
        }
    }

Pretty Simple. In my code I'm trying to this, but I don't know where I'm going wrong:

List<IContent> items;

MyDataContext cms = new MyDataContext();

items = cms.GetArticles();  
// ERROR: Can not implicitly convert List<Article> to List<IContent>

If my Article class implement IContent why can't I pass in Articles? I don't know what the objects that are going to be passed in.

I know I can do this with Inheriting a base class, but using LinqToSQL doesn't use regular objects.

I'm sure it's something simple that I'm missing.


Solution

  • Have you tried

    items = cms.GetArticles().Cast<IContent>().ToList();