Language: C#
Storing generic types in a list when they are constrained by an interface and new()
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(); } }
Report Abuse
Subscribe
Discuss
What's new
What is it
New Snippet
Recent Snippets
My Snippets
Web Code
Search


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>;
}
}