Anonymous Types and Interfaces

I finally had a chance to sit and work with LINQ for a bit, and while it is very cool, a little bit of its luster was lost when I can assign interfaces to the anonymous classes generated by the queries. Meaning I can not do something like:

public interface IExample
{
    string Name { get; set; }
    string Description { get; set; }
}
public class DataGenerator
{
    public IEnumerable<IExample> GetExamples(string categoryName)
    {
//Context Definition
IEnumerable<IExample> examples = from x in db.Examples
//LINQ to SQL Class
where x.Category.Name = categoryName select new IExamples { Name = x.Name
                                 , Description = x.Description } ; // There is probobly better syntax for this return examples; } }

Now I know I could instead do

public class Example
{
    public string Name { get; set; }
    public string Description { get; set; }
}
public class
DataGenerator
{
    public IEnumerable<Example> GetExamples(string categoryName)
    {
       
//Context Definition
        IEnumerable<Example> examples =
            from x in db.Examples
//LINQ to SQL Class,
            where x.Category.Name = categoryName
            select new Example{ Name = x.Name, Description = x.Description };

        return examples;
    }
}

or if I wanted to continue only exposing an interface

 

public interface IExample
{
    string Name { get; set; }
    string Description { get; set; }
}
internal class Example:IExample
{
    public string Name { get; set; }
    public string Description { get; set; }
}
public class DataGenerator
{
    public IEnumerable<IExample> GetExamples(string categoryName)
    {
        //LINQ to SQL Context Definition
        var examples =
            from x in db.Examples 
where x.Category.Name = categoryName select new Example{ Name = x.Name
                              , Description = x.Description }; return examples.OfType<IExample>(); } }

Over all this isn’t a big issue since the second method works just fine for what I am trying to accomplish for the most part. But it feels kind of off having to make a throwaway class to accomplish this.

Technorati Tags: , ,