New Snippet New Snippet Recent Snippets Recent Snippets My Snippets My Snippets Web Code Search Snippets Search
Sign inor Register
Language: C#

Storing generic types in a list when they are constrained by an interface and new()

72 Views
Copy Code Show/Hide Line Numbers
public class Container
{
    protected Container()
    {
        this.Foos = new List<IFooBuilder>();
    }
 
    public IList<IFooBuilder> Foos { get; set; }
 
    public FooBuilder<T> Foo<T>() where T : IFoo, new()
    {
        var builder =
            new FooBuilder<T>();
 
        this.Foos.Add(builder);
 
        return builder;
    }
 
    public IEnumerable<IFoo> GetFoos()
    {
        var foos =
            from builder in this.Foos
            select builder.GetBuiltInstance();
 
        return foos;
    }
}
 
/// <summary>
/// This interface makes it possible since it gives me a non-generic type to
/// cast all the generic types into when they are stored.
/// </summary>
public interface IFooBuilder
{
    IFoo GetBuiltInstance();
}
 
public class IFooBuilder<T> : IFooBuilder where T : IFoo, new()
{
    public IFoo GetBuiltInstance()
    {
        throw new NotImplementedException();
    }
}
by TheCodeJunkie
  January 29, 2010 @ 2:02pm

by Christopher Hyne    January 29, 2010 @ 3:16pm

What am I missing?

public class Container
{
protected Container()
{
this.Foos = new List<IFoo>();
}

public IList<IFoo> Foos { get; set; }

public IFoo Foo<T>() where T : IFoo, new()
{
var item = new T();

this.Foos.Add(item);

return item;
}

public IEnumerable<IFoo> GetFoos()
{
return this.Foos as IEnumerable<IFoo>;
}
}

by TheCodeJunkie    February 09, 2010 @ 2:25am

Its not creating T instances.. its creating FooBuilder<T> instances and T is constrained to IFoo, new()

Add a comment


Report Abuse
brought to you by:
West Wind Techologies


If you find this site useful and use it frequently please consider making a donation to support this free service.
Donate